package com.sinog.biz.service.api.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sinog.biz.mapper.havexml.PrisonerFxMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainMapper;
import com.sinog.biz.mapper.havexml.PrisonerSrMapper;
import com.sinog.biz.mapper.havexml.PrisonerZnMapper;
import com.sinog.biz.mapper.havexml.PrisonersZyjnMapper;
import com.sinog.biz.mapper.havexml.SystemCodeMapper;
import com.sinog.biz.mapper.havexml.XxblMapper;
import com.sinog.biz.service.api.DataTransmissionService;
import com.sinog.biz.service.api.async.AsyncUploadFileToFtp;
import com.sinog.biz.service.business.PrisonerFxBatchService;
import com.sinog.biz.service.business.PrisonerMainBatchService;
import com.sinog.biz.service.business.PrisonerSrBatchService;
import com.sinog.biz.service.business.PrisonerZnBatchService;
import com.sinog.biz.service.business.UploadAppendixFileBatchService;
import com.sinog.biz.service.business.XxblService;
import com.sinog.biz.service.business.impl.PrisonerMainServiceImpl;
import com.sinog.biz.util.Base64Util;
import com.sinog.biz.util.BusinessUtils;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.biz.util.FileUtil;
import com.sinog.biz.util.FtpUtil;
import com.sinog.biz.util.GdFtpUtil;
import com.sinog.biz.util.IdGen;
import com.sinog.biz.util.smlib.Sm4;
import com.sinog.core.domain.PrisaveTemp;
import com.sinog.core.domain.PrisonerFx;
import com.sinog.core.domain.PrisonerHc;
import com.sinog.core.domain.PrisonerMain;
import com.sinog.core.domain.PrisonerSr;
import com.sinog.core.domain.PrisonerZn;
import com.sinog.core.domain.PrisonersZyjn;
import com.sinog.core.domain.SystemCode;
import com.sinog.core.domain.UploadAppendixFiles;
import com.sinog.core.domain.UserInterFaceEntity;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.DateUtil;
import com.sinog.core.util.Hex;
import com.sinog.core.util.IdNumUtil;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.PhoneUtil;
import com.sinog.core.util.StrUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Dictionary;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author -
 * @desc 对外接口实现类
 * @date -
 */
@Slf4j
@Service
public class DataTransmissionServiceImpl implements DataTransmissionService {

    @Resource
    private PrisonerMainBatchService prisonerMainBatchService;
    @Resource
    private PrisonerFxBatchService prisonerFxBatchService;
    @Resource
    private PrisonerSrBatchService prisonerSrBatchService;
    @Resource
    private PrisonerZnBatchService prisonerZnBatchService;
    @Resource
    private UploadAppendixFileBatchService uploadAppendixFileBatchService;
    @Resource
    private PrisonerMainServiceImpl prisonerMainService;
    @Autowired
    private XxblService xxblService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SystemCodeMapper systemCodeMapper;
    @Resource
    private PrisonerMainMapper prisonerMainMapper;
    @Resource
    private PrisonerFxMapper prisonerFxMapper;
    @Resource
    private PrisonerSrMapper prisonerSrMapper;
    @Resource
    private PrisonerZnMapper prisonerZnMapper;
    @Resource
    PrisonersZyjnMapper prisonersZyjnMapper;
    @Resource
    private XxblMapper xxblMapper;
    @Autowired
    private AsyncUploadFileToFtp asyncUploadFileToFtp;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private GdFtpUtil gdFtpUtil;
    /**
     * 初始化字典表
     */
    private static final Dictionary DICTIONARY = Dictionary.getSingleton();
    /**
     * 对外接口鉴权超时时间
     */
    @Value("${gkzx.azbj.outerInterface.timeout}")
    private String timeout;
    /**
     * ftp存放目录
     */
    @Value("${gkzx.azbj.ftp.datapath}")
    private String datapath;

    /**
     * **********************************************************************************************************************************
     * *******************************************保存预安置人员*********************************************************
     * **********************************************************************************************************************************
     * @param data 原始json基础上封装user对象
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result savePreArrangedPersonnel(String data) {
        log.info("*******************************************保存预安置人员*********************************************************");
        // 1、定义返回结果
        Result r;
        // 2、打印biz入参日志
        // log.info("对外接口入参:{}",data);
        // 3、定义接口整体执行开始时间和封装开始时间
        long start = System.currentTimeMillis();
        long start1 = 0L;
        // 4、定义接口用户对象
        UserInterFaceEntity user = new UserInterFaceEntity();
        // 5、定义接口返回message信息
        StringBuilder stringBuilder = new StringBuilder(16);
        // 6、定义5张表数据对象，用于接收客户端传递的参数
        PrisonerMain prisonerMain = new PrisonerMain();
        List<UploadAppendixFiles> uploadAppendixFiles = new ArrayList<>(16);
        PrisonerFx prisonerFx = new PrisonerFx();
        List<PrisonerSr> prisonerSrs = new ArrayList<>(16);
        List<PrisonerZn> prisonerZns = new ArrayList<>(16);
        // 7、定义PrisaveTemp对象，当另外5张表都保存成功，则添加该表
        PrisaveTemp p = new PrisaveTemp();
        // 8、处理流程
        try {
            // 8.1、鉴权
            int jq = authentication(data);
            List<String> codes = new ArrayList<>(16);
            if(Constants.Number.NUM_ONE == jq) {
                stringBuilder.append("鉴权失败-超时。");
                codes.add("900001");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            if(Constants.Number.NUM_TWO == jq) {
                stringBuilder.append("鉴权失败-密钥错误。");
                codes.add("900002");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            if(Constants.Number.NUM_FU_ONE == jq) {
                stringBuilder.append("请传递时间戳！");
                codes.add("900003");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            if(Constants.Number.NUM_FU_TWO == jq) {
                stringBuilder.append("请传递接口密钥！");
                codes.add("900004");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            if(Constants.Number.NUM_FU_THREE == jq) {
                stringBuilder.append("请传递接口用户！");
                codes.add("900005");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            // 8.2、check
            Map<String,Object> check = check(data);
            boolean err = (Boolean)check.get("err");
            if(err) {
                List<String> errCodes = (List)check.get("result");
                return Result.failure(Constants.Number.NUM_FU_ONE,"参数校验不通过！",errCodes);
            } else {
                if(check.containsKey("PrisonerMain") && null != check.get("PrisonerMain")) {
                    prisonerMain = (PrisonerMain)check.get("PrisonerMain");
                }
                if(check.containsKey("MultimediaInfo") && null != check.get("MultimediaInfo")) {
                    uploadAppendixFiles = (List<UploadAppendixFiles>)check.get("MultimediaInfo");
                }
                if(check.containsKey("PrisonerFx") && null != check.get("PrisonerFx")) {
                    prisonerFx = (PrisonerFx)check.get("PrisonerFx");
                }
                if(check.containsKey("PrisonerSr") && null != check.get("PrisonerSr")) {
                    prisonerSrs = (List<PrisonerSr>)check.get("PrisonerSr");
                }
                if(check.containsKey("PrisonerZn") && null != check.get("PrisonerZn")) {
                    prisonerZns = (List<PrisonerZn>)check.get("PrisonerZn");
                }
                if(check.containsKey("user") && null != check.get("user")) {
                    user = (UserInterFaceEntity)check.get("user");
                }
            }
            // 8.3、组装数据
            assembled(user,prisonerMain,uploadAppendixFiles,prisonerFx,prisonerSrs,prisonerZns,p);
            // 9、生成犯罪编号
            String priNum = BusinessUtils.makePriNum(prisonerMainMapper,stringRedisTemplate,user.getDepartid(),user.getLevel());
            if(Constants.StrFinalValue.ERROR.equals(priNum)) {
                return Result.failure(ReturnCode.FAILURE);
            }
            r = saveT(prisonerMain,prisonerFx,uploadAppendixFiles,prisonerSrs,prisonerZns,p,priNum,user.getAccount(),user.getLevel());
        } catch(ClassCastException c) {
            log.error("发生异常:",c);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failure(ReturnCode.PARAM_TYPE_FAILURE);
        } catch(Exception e) {
            log.error("发生异常:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failure(ReturnCode.FAILURE);
        }
        log.info("预安置人员信息录入【总耗时】:{} ms",System.currentTimeMillis() - start);
        return r;
    }

    /**
     * 解除社区矫正接口
     * @param data data
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveJjData(String data) {
        // 1、定义返回结果
        Result r;
        // 2、打印biz入参日志
        log.info("解除社区接口--对外接口入参:{}",data);
        // 3、定义接口整体执行开始时间和封装开始时间
        long start = System.currentTimeMillis();
        // 4、定义接口用户对象
        UserInterFaceEntity user = new UserInterFaceEntity();
        // 5、定义接口返回message信息
        StringBuilder stringBuilder = new StringBuilder(16);
        // 6、定义5张表数据对象，用于接收客户端传递的参数
        PrisonerMain prisonerMain = new PrisonerMain();
        List<UploadAppendixFiles> uploadAppendixFiles = new ArrayList<>(16);
        PrisonerFx prisonerFx = new PrisonerFx();
        List<PrisonerSr> prisonerSrs = new ArrayList<>(16);
        List<PrisonerZn> prisonerZns = new ArrayList<>(16);
        // 7、定义PrisaveTemp对象，当另外5张表都保存成功，则添加该表
        PrisaveTemp p = new PrisaveTemp();
        // 8、处理流程
        try {
            // 8.1、鉴权
            int jq = authentication(data);
            List<String> codes = new ArrayList<>(16);
            if(Constants.Number.NUM_ONE == jq) {
                stringBuilder.append("鉴权失败-超时。");
                codes.add("900001");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            if(Constants.Number.NUM_TWO == jq) {
                stringBuilder.append("鉴权失败-密钥错误。");
                codes.add("900002");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            if(Constants.Number.NUM_FU_ONE == jq) {
                stringBuilder.append("请传递时间戳！");
                codes.add("900003");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            if(Constants.Number.NUM_FU_TWO == jq) {
                stringBuilder.append("请传递接口密钥！");
                codes.add("900004");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            if(Constants.Number.NUM_FU_THREE == jq) {
                stringBuilder.append("请传递接口用户！");
                codes.add("900005");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),codes);
            }
            // 8.2、check 基本信息
            Map<String,Object> check = check(data);
            boolean err = (Boolean)check.get("err");
            if(err) {
                List<String> errCodes = (List)check.get("result");
                return Result.failure(Constants.Number.NUM_FU_ONE,"参数校验不通过！",errCodes);
            } else {
                if(check.containsKey("PrisonerMain") && null != check.get("PrisonerMain")) {
                    prisonerMain = (PrisonerMain)check.get("PrisonerMain");
                }
                if(check.containsKey("MultimediaInfo") && null != check.get("MultimediaInfo")) {
                    uploadAppendixFiles = (List<UploadAppendixFiles>)check.get("MultimediaInfo");
                }
                if(check.containsKey("PrisonerFx") && null != check.get("PrisonerFx")) {
                    prisonerFx = (PrisonerFx)check.get("PrisonerFx");
                }
                if(check.containsKey("PrisonerSr") && null != check.get("PrisonerSr")) {
                    prisonerSrs = (List<PrisonerSr>)check.get("PrisonerSr");
                }
                if(check.containsKey("PrisonerZn") && null != check.get("PrisonerZn")) {
                    prisonerZns = (List<PrisonerZn>)check.get("PrisonerZn");
                }
                if(check.containsKey("user") && null != check.get("user")) {
                    user = (UserInterFaceEntity)check.get("user");
                }
            }
            Map<String,Object> checkcjpg = checkCjpg(data);
            boolean flag = (Boolean)checkcjpg.get("err");
            if(flag) {
                List<String> errCodes = (List)checkcjpg.get("result");
                return Result.failure(Constants.Number.NUM_FU_ONE,"参数校验不通过！",errCodes);
            }
            // 8.3、组装基本数据
            assembled(user,prisonerMain,uploadAppendixFiles,prisonerFx,prisonerSrs,prisonerZns,p);
            // 8.4、生成犯罪编号,保存基本信息
            String priNum = BusinessUtils.makePriNum(prisonerMainMapper,stringRedisTemplate,user.getDepartid(),user.getLevel());
            if(Constants.StrFinalValue.ERROR.equals(priNum)) {
                return Result.failure(ReturnCode.FAILURE);
            }
            r = saveT(prisonerMain,prisonerFx,uploadAppendixFiles,prisonerSrs,prisonerZns,p,priNum,user.getAccount(),user.getLevel());
            // 8.5、基本信息保存成功，发起核查、完成核查、职业技能、减刑假释、危险性评估、发起衔接、完成衔接逻辑
            if(Constants.Number.NUM_ONE.equals(r.getCode())) {
                Map<String,Object> stringObjectMap2 = JsonUtil.toMap(data);
                // 获得发起社区矫正用户信息
                Object newUser = stringObjectMap2.get("user");
                String newUserstr = "";
                if(null != newUser) {
                    newUserstr = newUser.toString();
                }
                UserInterFaceEntity userInterface = JsonUtil.toBean(newUserstr,UserInterFaceEntity.class);
                // 8.5.1、发起核查
                PrisonerHc prisonerHc = prisonerMainMapper.prisonerHcByPriNum(prisonerMain.getPriNum());
                Date date1 = new Date();
                prisonerHc.setUpdateTime(date1);
                prisonerHc.setUpdateUser(user.getAccount());
                prisonerHc.setCreateTime(date1);
                prisonerHc.setCreateUser(user.getAccount());
                prisonerHc.setStartCheckPerson(userInterface.getDepartName());
                prisonerHc.setStartCheckTime(date1);
                prisonerHc.setStartCheckPhone("");
                prisonerHc.setStartCheckTel("无");
                // 8.5.2、完成核查
                prisonerMain.setState(Constants.NumberStr.NUM_STR_THREE);
                prisonerMain.setStateXj(Constants.NumberStr.NUM_STR_FOUR);
                prisonerHc.setConnecttime(date1);
                prisonerHc.setConmectuserid(user.getAccount());
                prisonerHc.setConmectuserName(userInterface.getDepartName());
                prisonerHc.setConmectuserPhone("");
                prisonerHc.setPriReason("默认核查成功");
                prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
                prisonerMain.insertOrUpdate();
                prisonerHc.insert();
                // 8.5.3、职业技能
                Object zyjn = stringObjectMap2.get("zyjn");
                String zyjnstr = "";
                if(null != zyjn) {
                    zyjnstr = zyjn.toString();
                }
                PrisonersZyjn prisonersZyjn = JsonUtil.toBean(zyjnstr,PrisonersZyjn.class);
                prisonersZyjn.setCreateUser(user.getAccount());
                prisonersZyjn.setCreateTime(date1);
                prisonersZyjn.setUpdateUser(user.getAccount());
                prisonersZyjn.setUpdateTime(date1);
                prisonersZyjn.setCreateUser(user.getUsername());
                prisonersZyjn.setId(com.sinog.core.utilbean.IdGen.strid());
                prisonersZyjn.setPriNum(prisonerMain.getPriNum());
                prisonersZyjnMapper.insert(prisonersZyjn);
                // 8.5.4、减刑假释
                Object jxjs = stringObjectMap2.get("jxjs");
                String jxjsstr = "";
                if(null != jxjs) {
                    jxjsstr = jxjs.toString();
                }
                Map<String,Object> stringObjectMap = JsonUtil.toMap(jxjsstr);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                String priStopTemp = stringObjectMap.get("priStop").toString();
                Date priStop = null;
                if(StringUtils.isNotEmpty(priStopTemp)) {
                    priStop = simpleDateFormat1.parse(stringObjectMap.get("priStop").toString());
                }
                String subRange = (String)stringObjectMap.get("subRange");
                String priStopOld = (String)stringObjectMap.get("pristopold");
                String createUser = user.getUsername();
                String id = com.sinog.core.utilbean.IdGen.strid();
                prisonerFx.setPriStop(priStop);
                prisonerFx.setRemark(priStopOld);
                prisonerFx.setPritime(subRange);
                xxblMapper.saveJxjsInfo(id,subRange,priStop,prisonerMain.getPriNum(),createUser,priStopOld,date1);
                prisonerFxMapper.updatePriStopAndPritime(prisonerMain.getPriNum(),priStop,priStopOld,subRange,user.getAccount(),date1);
                // 8.5.5、出监、危险性评估
                Object cjpg = stringObjectMap2.get("cjpg");
                String cjpgstr = "";
                if(null != cjpg) {
                    cjpgstr = cjpg.toString();
                }
                Map<String,Object> jsonMap = JsonUtil.toMap(cjpgstr);
                if(Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("sanwu")) || Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("sanjia")) || Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("weifa"))) {
                    // 重点帮教对象
                    jsonMap.put("pinggu",Constants.NumberStr.NUM_STR_ZERO_ONE);
                } else {
                    // 一般帮教对象
                    jsonMap.put("pinggu",Constants.NumberStr.NUM_STR_ZERO_TWO);
                }
                jsonMap.put("priNum",prisonerMain.getPriNum());
                Result cjpgResult;
                cjpgResult = prisonerMainService.insertCjpg(jsonMap);
                if(Constants.Number.NUM_ONE.equals(cjpgResult.getCode())) {
                    jsonMap.remove("id");
                    String s = JsonUtil.toText(jsonMap);
                    xxblService.saveWxxpgInfo(s);
                }
                // 8.5.6、监狱发起衔接
                Map<String,Object> stringObjectMap1 = new HashMap<>(16);
                String departid = user.getDepartid();
                String departName = user.getDepartName();
                String account = user.getAccount();
                if(Constants.NumberStr.NUM_STR_ZERO_ONE.equals(jsonMap.get("pinggu"))) {
                    // 重点帮教对象
                    stringObjectMap1.put("type",Constants.NumberStr.NUM_STR_ZERO_ONE);
                    // 监狱送回
                    stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_ZERO_ONE);
                } else {
                    // 一般帮教对象
                    stringObjectMap1.put("type",Constants.NumberStr.NUM_STR_ZERO_TWO);
                    if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(jsonMap.get("pinggu"))) {
                        boolean flag1 = Constants.NumberStr.NUM_STR_ZERO_ONE.equals(jsonMap.get("wushe")) && ("true".equals(jsonMap.get("shehei")) || "true".equals(jsonMap.get("shekong")));
                        if(flag1) {
                            // 监狱送回
                            stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_ZERO_ONE);
                        } else {
                            // 基层组织及家属接回 或人员自返04
                            stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_ZERO_THREE);
                        }
                    } else {
                        if(Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("weifa")) && Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("Aftype"))) {
                            // 监狱送回
                            stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_ZERO_ONE);
                        } else {
                            if(Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("sanjia")) && Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("sanwu"))) {
                                // 基层组织及家属接回
                                stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_ZERO_THREE);
                                // stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_FU_ONE);人员自返
                            } else if(Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("sanjia")) && !Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("sanwu"))) {
                                // 基层组织及家属接回
                                stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_ZERO_THREE);
                                // stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_FU_ONE);人员自返
                            } else if(!Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("sanjia")) && Constants.NumberStr.NUM_STR_ONE.equals(jsonMap.get("sanwu"))) {
                                // 基层组织及家属接回
                                stringObjectMap1.put("zhongdian",Constants.NumberStr.NUM_STR_ZERO_THREE);
                            }
                        }
                    }
                }
                stringObjectMap1.put("dianhua","");
                stringObjectMap1.put("lianxiren",departName);
                stringObjectMap1.put("jhsj",prisonerFx.getPriStop());
                stringObjectMap1.put("priNum",prisonerMain.getPriNum());
                // tujing 默认监狱释放
                stringObjectMap1.put("tujing",Constants.NumberStr.NUM_STR_ZERO_ONE);
                String s = JsonUtil.toText(stringObjectMap1);
                prisonerMainService.insertXjxx(s,departid,departName,account);
                // 8.5.7、司法所完成衔接
                Map<String,Object> jsonMap1 = new HashMap<>(16);
                jsonMap1.put("priNum",prisonerMain.getPriNum());
                // 衔接状态，默认是1
                jsonMap1.put("statexj",Constants.NumberStr.NUM_STR_ONE);
                // 开始第二次衔接流程状态：社区矫正默认-1
                jsonMap1.put("secondStateXj",Constants.NumberStr.NUM_STR_FU_ONE);
                // 安置帮教人员类别 社区矫正安置帮教人员类别默认为03
                jsonMap1.put("abpersontype",Constants.NumberStr.NUM_STR_ZERO_THREE);
                String s1 = JsonUtil.toText(jsonMap1);
                prisonerMainService.updateCompletelyData(s1,JsonUtil.toBean(JsonUtil.toText(user),UserDTO.class));
            }
        } catch(Exception e) {
            log.error("发生异常:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failure(ReturnCode.FAILURE);
        }
        log.info("解除社区接口【总耗时】:{} ms",System.currentTimeMillis() - start);
        return r;
    }

    /**
     * 1、鉴权： 对比密钥，比对失败，鉴权失败，客户端时间戳超出x分钟鉴权失败
     * @param data 原始json基础上封装user对象
     * @return int
     */
    private int authentication(String data) {
        try {
            Map<String,Object> maps = JsonUtil.toMap(data);
            String time;
            if(null != maps.get("time") && !"".equals(maps.get("time").toString())) {
                time = maps.get("time").toString();
            } else {
                return -1;
            }
            String sign;
            if(null != maps.get("sign") && !"".equals(maps.get("sign").toString())) {
                sign = maps.get("sign").toString();
            } else {
                return -2;
            }
            UserInterFaceEntity userDTO = JsonUtil.toBean(maps.get("user").toString(),UserInterFaceEntity.class);
            String uid = userDTO.getUid();
            if(StringUtils.isEmpty(uid)) {
                return -3;
            }
            // 计算入参时间time和当前系统时间分钟差
            long pastTime = DateUtil.getPastTime(Long.parseLong(time));
            if(pastTime > Integer.parseInt(timeout) || -10L > pastTime) {
                log.info("服务器时间{},客户端时间{}",System.currentTimeMillis(),time);
                log.info("接口时间戳时间异常，超时{}分钟！",timeout);
                return 1;
            }
            // 服务端生成的密钥
            String sec = Hex.getSignatureKey(uid,time,"/transmission/api/azbj/savePreArrangedPersonnel/");
            if(!sec.equals(sign)) {
                log.error("接口密钥{}错误",sign);
                return 2;
            }
        } catch(NumberFormatException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("发生异常:",e);
        }
        return 0;
    }

    /**
     * 2、校验接口入参
     * @param data 原始json基础上封装user对象
     * @return Map<String,Object>
     */
    private Map<String,Object> check(String data) {
        // 用于保存返回的错误code集合
        List<String> errCodes = new ArrayList<>(16);
        long start = System.currentTimeMillis();
        // StringBuilder errMessage = new StringBuilder(16);
        Map<String,Object> result = new HashMap<>(16);
        Map<String,Object> maps = JsonUtil.toMap(data);
        UserInterFaceEntity userDTO = JsonUtil.toBean(maps.get("user").toString(),UserInterFaceEntity.class);
        // 取出各表不需要校验的字段
        String unCheckField = userDTO.getUnCheckField();
        log.info(unCheckField);
        String[] strs = unCheckField.split("\\|");
        List<String> mains = Arrays.asList(strs[0].split(","));
        List<String> imgs = Arrays.asList(strs[1].split(","));
        List<String> fxs = Arrays.asList(strs[2].split(","));
        List<String> srs = Arrays.asList(strs[3].split(","));
        List<String> zns = Arrays.asList(strs[4].split(","));
        Map<String,Object> prisonerMainMap;
        if(null != maps.get("PrisonerMain") && !"".equals(maps.get("PrisonerMain").toString())) {
            prisonerMainMap = JsonUtil.toMap(maps.get("PrisonerMain").toString());
        } else {
            prisonerMainMap = new HashMap<>(16);
        }
        List<UploadAppendixFiles> multimediaInfos;
        if(null != maps.get("MultimediaInfo") && !"".equals(maps.get("MultimediaInfo").toString())) {
            multimediaInfos = JsonUtil.toList(maps.get("MultimediaInfo").toString(),UploadAppendixFiles.class);
        } else {
            multimediaInfos = new ArrayList<>(16);
        }
        Map<String,Object> prisonerFxMap;
        if(null != maps.get("PrisonerFx") && !"".equals(maps.get("PrisonerFx").toString())) {
            prisonerFxMap = JsonUtil.toMap(maps.get("PrisonerFx").toString());
        } else {
            prisonerFxMap = new HashMap<>(16);
        }
        List<PrisonerSr> prisonerSrs;
        if(null != maps.get("PrisonerSr") && !"".equals(maps.get("PrisonerSr").toString())) {
            prisonerSrs = JsonUtil.toList(maps.get("PrisonerSr").toString(),PrisonerSr.class);
        } else {
            prisonerSrs = new ArrayList<>(16);
        }
        List<PrisonerZn> prisonerZns;
        if(null != maps.get("PrisonerZn") && !"".equals(maps.get("PrisonerZn").toString())) {
            prisonerZns = JsonUtil.toList(maps.get("PrisonerZn").toString(),PrisonerZn.class);
        } else {
            prisonerZns = new ArrayList<>(16);
        }
        PrisonerMain prisonerMain = new PrisonerMain();
        PrisonerFx prisonerFx = null;
        Boolean priBeginFlag = false;
        // 1、check主表
        {
            for(Map.Entry<String,Object> next : prisonerMainMap.entrySet()) {
                Object obj = next.getValue();
                if(obj instanceof String) {
                    next.setValue(((String)obj).trim());
                }
            }
            // 取出prisonerMainMap并校验
            String pName = (String)prisonerMainMap.get("pName");
            String usedName = (String)prisonerMainMap.get("usedName");
            String sex = (String)prisonerMainMap.get("sex");
            String nationality = (String)prisonerMainMap.get("nationality");
            String idType = (String)prisonerMainMap.get("idType");
            String idNum = (String)prisonerMainMap.get("idNum");
            //如果姓名和身份证号都不为空，则根据姓名和身份证查询系统是否存在该人员
            if(!StringUtils.isEmpty(pName) && !StringUtils.isEmpty(idNum)) {
                if(!"无".equals(idNum)) {
                    PrisonerMain newPrisonerMain = prisonerMainMapper.verifyIdNumer(Sm4.encryptEcb(idNum),pName);
                    if(null != newPrisonerMain) {
                        priBeginFlag = true;
                        String priNum = newPrisonerMain.getPriNum();
                        PrisonerFx newPrisonerFx = prisonerFxMapper.selectOne(new QueryWrapper<PrisonerFx>().lambda()
                                                                                                            .eq(PrisonerFx::getPriNum,priNum)
                                                                                                            .last("limit 1"));
                        if(null != newPrisonerFx) {
                            String pritime = newPrisonerFx.getPritime();
                            if(StrUtil.contains(pritime,Constants.PritimeTypeNow.PRITIME_WUQI,Constants.PritimeTypeNow.PRITIME_SIHUAN,Constants.PritimeTypeNow.PRITIME_SIXING)) {
                                // 该服刑人员未出狱
                                errCodes.add("99999");
                            }
                            Date date = new Date();
                            if(null != newPrisonerFx.getPriStopNow()) {
                                if(newPrisonerFx.getPriStopNow().getTime() > date.getTime()) {
                                    // 该服刑人员未出狱
                                    errCodes.add("99999");
                                }
                            } else if(null == newPrisonerFx.getPriStopNow() && null != newPrisonerFx.getPriStop()) {
                                if(newPrisonerFx.getPriStop().getTime() > date.getTime()) {
                                    // 该服刑人员未出狱
                                    errCodes.add("99999");
                                }
                            }
                        } else if(null == newPrisonerFx) {
                            // 该服刑人员未出狱
                            errCodes.add("99999");
                        }
                    }
                }
            }
            String age;
            if(prisonerMainMap.get("age") instanceof Long) {
                long age1 = (long)prisonerMainMap.get("age");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                age = sdf.format(new Date(age1));
            } else {
                age = (String)prisonerMainMap.get("age");
            }
            String addtime;
            if(prisonerMainMap.get("addtime") instanceof Long) {
                long addtime1 = (long)prisonerMainMap.get("addtime");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                addtime = sdf.format(new Date(addtime1));
            } else {
                addtime = (String)prisonerMainMap.get("addtime");
            }
            String education = (String)prisonerMainMap.get("education");
            String priAddr = (String)prisonerMainMap.get("priAddr");
            String nativepro = (String)prisonerMainMap.get("nativepro");
            //todo 针对于重庆的省直辖区县做单独处理，后续取消
            String nativecity = cityCheck((String)prisonerMainMap.get("nativecity"));
            String nativecou = (String)prisonerMainMap.get("nativecou");
            String nativevill = (String)prisonerMainMap.get("nativevill");
            String nativenum = (String)prisonerMainMap.get("nativenum");
            String placepro = (String)prisonerMainMap.get("placepro");
            //todo 针对于重庆的省直辖区县做单独处理，后续取消
            String placecity = cityCheck((String)prisonerMainMap.get("placecity"));
            String placecou = (String)prisonerMainMap.get("placecou");
            String placevill = (String)prisonerMainMap.get("placevill");
            String placenum = (String)prisonerMainMap.get("placenum");
            String arrestpro = (String)prisonerMainMap.get("arrestpro");
            //todo 针对于重庆的省直辖区县做单独处理，后续取消
            String arrestcity = cityCheck((String)prisonerMainMap.get("arrestcity"));
            String arrestcou = (String)prisonerMainMap.get("arrestcou");
            String arrestvill = (String)prisonerMainMap.get("arrestvill");
            String arrestnum = (String)prisonerMainMap.get("arrestnum");
            String investigatePro = (String)prisonerMainMap.get("investigatePro");
            //todo 针对于重庆的省直辖区县做单独处理，后续取消
            String investigateCity = cityCheck((String)prisonerMainMap.get("investigateCity"));
            String investigateCou = (String)prisonerMainMap.get("investigateCou");
            String investigateVill = (String)prisonerMainMap.get("investigateVill");
            String investigateNum = (String)prisonerMainMap.get("investigateNum");
            // 校验
            if(!mains.contains("pName") && StringUtils.isEmpty(pName)) {
                // errMessage.append("预安置人员 姓名不能为空。");
                errCodes.add("100001");
            }
            if(!mains.contains("pName") && !StringUtils.isEmpty(pName) && 30 < pName.length()) {
                // errMessage.append("预安置人员 姓名长度不能超过30。");
                errCodes.add("100002");
            }
            if(!mains.contains("usedName") && !StringUtils.isEmpty(usedName) && 30 < usedName.length()) {
                // errMessage.append("预安置人员 曾用名长度不能超过30。");
                errCodes.add("100003");
            }
            if(!mains.contains("sex") && StringUtils.isEmpty(sex)) {
                // errMessage.append("预安置人员 性别不能为空。");
                errCodes.add("100004");
            }
            if(!mains.contains("sex") && !StringUtils.isEmpty(sex) && !StrUtil.containsEquals(sex,DICTIONARY.getsex())) {
                // errMessage.append("预安置人员 性别不正确。");
                errCodes.add("100005");
            }
            if(!mains.contains("nationality") && StringUtils.isEmpty(nationality)) {
                // errMessage.append("预安置人员 民族不能为空。");
                errCodes.add("100006");
            }
            if(!mains.contains("nationality") && !StringUtils.isEmpty(nationality) && !StrUtil.containsEquals(nationality,DICTIONARY.getnationality())) {
                // errMessage.append("预安置人员 民族编码不正确。");
                errCodes.add("100007");
            }
            if(!mains.contains("idType") && StringUtils.isEmpty(idType)) {
                // errMessage.append("预安置人员 证件类型不能为空。");
                errCodes.add("100040");
            }
            if(!mains.contains("idType") && !StringUtils.isEmpty(idType) && !StrUtil.containsEquals(idType,DICTIONARY.getIdType())) {
                // errMessage.append("预安置人员 证件类型编码不正确。");
                errCodes.add("100041");
            }
            if(!mains.contains("idNum") && !StringUtils.isEmpty(idNum) && Constants.NumberStr.NUM_STR_ONE.equals(idType)) {
                if((18 != idNum.length()) && (15 != idNum.length())) {
                    errCodes.add("100008");
                }
            }
            if(!mains.contains("age") && !StringUtils.isEmpty(age) && DateUtil.checkStrDate(age)) {
                // errMessage.append("预安置人员 出生日期不正确。");
                errCodes.add("100009");
            }
            if(!mains.contains("addtime") && StringUtils.isEmpty(addtime)) {
                // errMessage.append("预安置人员 入监日期不能为空。");
                errCodes.add("100010");
            }
            if(!mains.contains("addtime") && !StringUtils.isEmpty(addtime) && DateUtil.checkStrDate(addtime)) {
                // errMessage.append("预安置人员 入监日期不正确。");
                errCodes.add("100011");
            }
            if(!mains.contains("addtime") && !mains.contains("age") && !StringUtils.isEmpty(addtime) && !StringUtils.isEmpty(age) && 0 > addtime.compareTo(age)) {
                // errMessage.append("预安置人员 入监日期不能大于出生日期。");
                errCodes.add("100012");
            }
            if(!mains.contains("education") && StringUtils.isEmpty(education)) {
                // errMessage.append("预安置人员 文化程度不能为空。");
                errCodes.add("100013");
            }
            if(!mains.contains("education") && !StringUtils.isEmpty(education) && !StrUtil.containsEquals(education,DICTIONARY.geteducation())) {
                // errMessage.append("预安置人员 文化程度编码不正确。");
                errCodes.add("100014");
            }
            if(!mains.contains("priAddr") && StringUtils.isEmpty(priAddr)) {
                // errMessage.append("预安置人员 户籍类型编码不能为空。");
                errCodes.add("100015");
            }
            if(!mains.contains("priAddr") && !StringUtils.isEmpty(priAddr) && !StrUtil.containsEquals(priAddr,DICTIONARY.getpriaddr())) {
                // errMessage.append("预安置人员 户籍类型编码不正确。");
                errCodes.add("100016");
            }
            if(!mains.contains("nativepro") && StringUtils.isEmpty(nativepro)) {
                // errMessage.append("预安置人员 户籍地址省份编码不能为空。");
                errCodes.add("100017");
            } else {
                if(!mains.contains("nativecity") && StringUtils.isEmpty(nativecity)) {
                    // errMessage.append("预安置人员 户籍地址地市编码不能为空。");
                    errCodes.add("100018");
                } else {
                    if(!mains.contains("nativecou") && StringUtils.isEmpty(nativecou)) {
                        // errMessage.append("预安置人员 户籍地址区县编码不能为空。");
                        errCodes.add("100019");
                    }
                }
            }
            boolean nativeproErrFlag = false;
            boolean nativecityErrFlag = false;
            boolean nativecouErrFlag = false;
            boolean nativevillErrFlag = false;
            if(!StringUtils.isEmpty(nativepro)) {
                String pCodePro = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",nativepro);
                if(!mains.contains("nativepro") && !Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                    // errMessage.append("预安置人员 户籍地址编码不正确。");
                    errCodes.add("100020");
                } else if(mains.contains("nativepro") && !Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                    //nativepro错了，需要将下面行政区划都置为空
                    nativeproErrFlag = true;
                } else {
                    if(!StringUtils.isEmpty(nativecity)) {
                        String pCodeCity = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",nativecity);
                        if(!mains.contains("nativecity") && !nativepro.equals(pCodeCity)) {
                            // errMessage.append("预安置人员 户籍地址编码不正确。");
                            errCodes.add("100020");
                        } else if(mains.contains("nativecity") && !nativepro.equals(pCodeCity)) {
                            //nativecity错了，需要将下面行政区划都置为空
                            nativecityErrFlag = true;
                        } else {
                            if(!StringUtils.isEmpty(nativecou)) {
                                String pCodeCou = (String)stringRedisTemplate.opsForHash()
                                                                             .get("areaCodeAndPcode",nativecou);
                                if(!mains.contains("nativecou") && !nativecity.equals(pCodeCou)) {
                                    // errMessage.append("预安置人员 户籍地址编码不正确。");
                                    errCodes.add("100020");
                                } else if(mains.contains("nativecou") && !nativecity.equals(pCodeCou)) {
                                    //nativecou错了，需要将下面行政区划都置为空
                                    nativecouErrFlag = true;
                                } else {
                                    if(!StringUtils.isEmpty(nativevill)) {
                                        String pCodeVill = (String)stringRedisTemplate.opsForHash()
                                                                                      .get("areaCodeAndPcode",nativevill);
                                        if(!mains.contains("nativevill") && !nativecou.equals(pCodeVill)) {
                                            // errMessage.append("预安置人员 户籍地址编码不正确。");
                                            errCodes.add("100020");
                                        } else if(mains.contains("nativevill") && !nativecou.equals(pCodeVill)) {
                                            //nativecou错了，需要将下面行政区划都置为空
                                            nativevillErrFlag = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(!mains.contains("nativenum") && StringUtils.isEmpty(nativenum)) {
                // errMessage.append("预安置人员 户籍详细地址不能为空。");
                errCodes.add("100021");
            }
            if(!mains.contains("nativenum") && !StringUtils.isEmpty(nativenum) && 50 < nativenum.length()) {
                // errMessage.append("预安置人员 户籍详细地址长度不能超过50。");
                errCodes.add("100022");
            }
            boolean placeproErrFlag = false;
            boolean placecityErrFlag = false;
            boolean placecouErrFlag = false;
            boolean placevillErrFlag = false;
            if(!StringUtils.isEmpty(placepro)) {
                String pCodePro = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",placepro);
                if(!mains.contains("placepro") && !Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                    // errMessage.append("预安置人员 居住地址编码不正确。");
                    errCodes.add("100023");
                } else if(mains.contains("placepro") && !Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                    placeproErrFlag = true;
                } else {
                    if(!StringUtils.isEmpty(placecity)) {
                        String pCodeCity = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",placecity);
                        if(!mains.contains("placecity") && !placepro.equals(pCodeCity)) {
                            // errMessage.append("预安置人员 居住地址编码不正确。");
                            errCodes.add("100023");
                        } else if(mains.contains("placecity") && !placepro.equals(pCodeCity)) {
                            placecityErrFlag = true;
                        } else {
                            if(!StringUtils.isEmpty(placecou)) {
                                String pCodeCou = (String)stringRedisTemplate.opsForHash()
                                                                             .get("areaCodeAndPcode",placecou);
                                if(!mains.contains("placecou") && !placecity.equals(pCodeCou)) {
                                    // errMessage.append("预安置人员 居住地址编码不正确。");
                                    errCodes.add("100023");
                                } else if(mains.contains("placecou") && !placecity.equals(pCodeCou)) {
                                    placecouErrFlag = true;
                                } else {
                                    if(!StringUtils.isEmpty(placevill)) {
                                        String pCodeVill = (String)stringRedisTemplate.opsForHash()
                                                                                      .get("areaCodeAndPcode",placevill);
                                        if(!mains.contains("placevill") && !placecou.equals(pCodeVill)) {
                                            // errMessage.append("预安置人员 居住地址编码不正确。");
                                            errCodes.add("100023");
                                        } else if(mains.contains("placevill") && !placecou.equals(pCodeVill)) {
                                            placevillErrFlag = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(!mains.contains("placepro") && !mains.contains("placecity") && !mains.contains("placecou") && !mains.contains("placevill")) {
                boolean flag = (!StringUtils.isEmpty(placevill) && (StringUtils.isEmpty(placepro) || StringUtils.isEmpty(placecity) || StringUtils.isEmpty(placecou))) || (!StringUtils.isEmpty(placecou) && (StringUtils.isEmpty(placepro) || StringUtils.isEmpty(placecity))) || (!StringUtils.isEmpty(placecity) && StringUtils.isEmpty(placepro));
                if(flag) {
                    // errMessage.append("预安置人员 居住地址编码上级未填写。");
                    errCodes.add("100024");
                }
            }
            if(!mains.contains("placenum") && !StringUtils.isEmpty(placenum) && 50 < placenum.length()) {
                // errMessage.append("预安置人员 居住地详细地址长度不能超过50。");
                errCodes.add("100025");
            }
            // 户籍为查不清户籍，需要校验原侦查机关地址
            if(Constants.NumberStr.NUM_STR_ZERO_THREE.equals(priAddr)) {
                if(!mains.contains("investigatePro") && StringUtils.isEmpty(investigatePro)) {
                    // errMessage.append("预安置人员 原侦查机关地址省份编码不能为空。");
                    errCodes.add("100026");
                } else {
                    if(!mains.contains("investigateCity") && StringUtils.isEmpty(investigateCity)) {
                        // errMessage.append("预安置人员 原侦查机关地址地市编码不能为空。");
                        errCodes.add("100027");
                    } else {
                        if(!mains.contains("investigateCou") && StringUtils.isEmpty(investigateCou)) {
                            // errMessage.append("预安置人员 原侦查机关地址区县编码不能为空。");
                            errCodes.add("100028");
                        } else {
                            if(!mains.contains("investigateVill") && StringUtils.isEmpty(investigateVill)) {
                                // errMessage.append("预安置人员 原侦查机关地址乡镇街道编码不能为空。");
                                errCodes.add("100029");
                            }
                        }
                    }
                }
                if(!StringUtils.isEmpty(investigatePro)) {
                    String pCodePro = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",investigatePro);
                    if(!Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                        // errMessage.append("预安置人员 原侦查机关地址编码不正确。");
                        errCodes.add("100030");
                    } else {
                        if(!StringUtils.isEmpty(investigateCity)) {
                            String pCodeCity = (String)stringRedisTemplate.opsForHash()
                                                                          .get("areaCodeAndPcode",investigateCity);
                            if(!investigatePro.equals(pCodeCity)) {
                                // errMessage.append("预安置人员 原侦查机关地址编码不正确。");
                                errCodes.add("100030");
                            } else {
                                if(!StringUtils.isEmpty(investigateCou)) {
                                    String pCodeCou = (String)stringRedisTemplate.opsForHash()
                                                                                 .get("areaCodeAndPcode",investigateCou);
                                    if(!investigateCity.equals(pCodeCou)) {
                                        // errMessage.append("预安置人员 原侦查机关地址编码不正确。");
                                        errCodes.add("100030");
                                    } else {
                                        if(!StringUtils.isEmpty(investigateVill)) {
                                            String pCodeVill = (String)stringRedisTemplate.opsForHash()
                                                                                          .get("areaCodeAndPcode",investigateVill);
                                            if(!investigateCou.equals(pCodeVill)) {
                                                // errMessage.append("预安置人员 原侦查机关地址编码不正确。");
                                                errCodes.add("100030");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(!mains.contains("investigateNum") && StringUtils.isEmpty(investigateNum)) {
                    // errMessage.append("预安置人员 原侦查机关详细地址不能为空。");
                    errCodes.add("100031");
                }
                if(!mains.contains("investigateNum") && !StringUtils.isEmpty(investigateNum) && 50 < investigateNum.length()) {
                    // errMessage.append("预安置人员 原侦查机关详细地址长度不能超过50。");
                    errCodes.add("100032");
                }
            }
            // 校验非大陆户籍 priAddr为"04","05","06","07","08"
            if(StrUtil.containsEquals(priAddr,DICTIONARY.getfdlpriaddr())) {
                if(!mains.contains("arrestpro") && StringUtils.isEmpty(arrestpro)) {
                    // errMessage.append("预安置人员 逮捕机关地址省份编码不能为空。");
                    errCodes.add("100033");
                } else {
                    if(!mains.contains("arrestcity") && StringUtils.isEmpty(arrestcity)) {
                        // errMessage.append("预安置人员 逮捕机关地址地市编码不能为空。");
                        errCodes.add("100034");
                    } else {
                        if(!mains.contains("arrestcou") && StringUtils.isEmpty(arrestcou)) {
                            // errMessage.append("预安置人员 逮捕机关地址区县编码不能为空。");
                            errCodes.add("100035");
                        } else {
                            if(!mains.contains("arrestvill") && StringUtils.isEmpty(arrestvill)) {
                                // errMessage.append("预安置人员 逮捕机关地址乡镇街道编码不能为空。");
                                errCodes.add("100036");
                            }
                        }
                    }
                }
                if(!StringUtils.isEmpty(arrestpro)) {
                    String pCodePro = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",arrestpro);
                    if(!Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                        // errMessage.append("预安置人员 逮捕机关地址编码不正确。");
                        errCodes.add("100037");
                    } else {
                        if(!StringUtils.isEmpty(arrestcity)) {
                            String pCodeCity = (String)stringRedisTemplate.opsForHash()
                                                                          .get("areaCodeAndPcode",arrestcity);
                            if(!arrestpro.equals(pCodeCity)) {
                                // errMessage.append("预安置人员 逮捕机关地址编码不正确。");
                                errCodes.add("100037");
                            } else {
                                if(!StringUtils.isEmpty(arrestcou)) {
                                    String pCodeCou = (String)stringRedisTemplate.opsForHash()
                                                                                 .get("areaCodeAndPcode",arrestcou);
                                    if(!arrestcity.equals(pCodeCou)) {
                                        // errMessage.append("预安置人员 逮捕机关地址编码不正确。");
                                        errCodes.add("100037");
                                    } else {
                                        if(!StringUtils.isEmpty(arrestvill)) {
                                            String pCodeVill = (String)stringRedisTemplate.opsForHash()
                                                                                          .get("areaCodeAndPcode",arrestvill);
                                            if(!arrestcou.equals(pCodeVill)) {
                                                // errMessage.append("预安置人员 逮捕机关地址编码不正确。");
                                                errCodes.add("100037");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(!mains.contains("arrestnum") && StringUtils.isEmpty(arrestnum)) {
                    // errMessage.append("预安置人员 逮捕机关详细地址不能为空。");
                    errCodes.add("100038");
                }
                if(!mains.contains("arrestnum") && !StringUtils.isEmpty(arrestnum) && 50 < arrestnum.length()) {
                    // errMessage.append("预安置人员 逮捕机关详细地址长度不能超过50。");
                    errCodes.add("100039");
                }
            }
            // 封装实体类，设置一些默认项
            if(errCodes.isEmpty()) {
                String json = JSON.toJSONString(prisonerMainMap);
                prisonerMain = JsonUtil.toBean(json,PrisonerMain.class);
                // 如果证件类型为身份证，生日是空，默认设置生日为省份证中出生日期
                if(Constants.NumberStr.NUM_STR_ONE.equals(idType) && !StringUtils.isEmpty(idNum) && 18 == idNum.length() && StringUtils.isEmpty(age)) {
                    // 身份证不为空，并且为18位身份证，设置生日为身份证的7～14位
                    String year = idNum.substring(6,10);
                    String month = idNum.substring(10,12);
                    String day = idNum.substring(12,14);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date birthday = null;
                    try {
                        // 注意格式需要与上面一致，不然会出现异常
                        birthday = sdf.parse(new StringBuffer(year).append("-").append(month).append("-").append(day)
                                                                   .toString());
                    } catch(ParseException e) {
                        log.error("发生异常:",e);
                    }
                    prisonerMain.setAge(birthday);
                }
                prisonerMain.setAdduserid(userDTO.getDepartid());
                prisonerMain.setAddusername(userDTO.getUsername());
                prisonerMain.setPdanwei(userDTO.getDepartid());
                prisonerMain.setPdanweiName(userDTO.getDepartName());
                // 城镇、农村
                if(Constants.NumberStr.NUM_STR_ZERO_ONE.equals(priAddr) || Constants.NumberStr.NUM_STR_ZERO_TWO.equals(priAddr)) {
                    prisonerMain.setHjType(Constants.NumberStr.NUM_STR_ZERO_ONE);
                    prisonerMain.setDetailType("");
                    if(nativeproErrFlag) {
                        prisonerMain.setNativepro("");
                        prisonerMain.setNativecity("");
                        prisonerMain.setNativecou("");
                        prisonerMain.setNativevill("");
                    } else if(nativecityErrFlag) {
                        prisonerMain.setNativecity("");
                        prisonerMain.setNativecou("");
                        prisonerMain.setNativevill("");
                    } else if(nativecouErrFlag) {
                        prisonerMain.setNativecou("");
                        prisonerMain.setNativevill("");
                    } else if(nativevillErrFlag) {
                        prisonerMain.setNativevill("");
                    }
                    if(placeproErrFlag) {
                        prisonerMain.setPlacepro("");
                        prisonerMain.setPlacecity("");
                        prisonerMain.setPlacecou("");
                        prisonerMain.setPlacevill("");
                    } else if(placecityErrFlag) {
                        prisonerMain.setPlacecity("");
                        prisonerMain.setPlacecou("");
                        prisonerMain.setPlacevill("");
                    } else if(placecouErrFlag) {
                        prisonerMain.setPlacecou("");
                        prisonerMain.setPlacevill("");
                    } else if(placevillErrFlag) {
                        prisonerMain.setPlacevill("");
                    }
                } else if(Constants.NumberStr.NUM_STR_ZERO_THREE.equals(priAddr)) {
                    // 查不清，设置原侦查机关
                    prisonerMain.setPriAddr(Constants.NumberStr.NUM_STR_ZERO_ONE);
                    prisonerMain.setHjType(Constants.NumberStr.NUM_STR_ZERO_TWO);
                    prisonerMain.setDetailType("");
                    prisonerMain.setInvestigatePro(investigatePro);
                    prisonerMain.setInvestigateCity(investigateCity);
                    prisonerMain.setInvestigateCou(investigateCou);
                    prisonerMain.setInvestigateVill(investigateVill);
                    prisonerMain.setInvestigateNum(investigateNum);
                    prisonerMain.setNativepro("");
                    prisonerMain.setNativecity("");
                    prisonerMain.setNativecou("");
                    prisonerMain.setNativevill("");
                    prisonerMain.setNativenum("");
                    prisonerMain.setPlacepro("");
                    prisonerMain.setPlacecity("");
                    prisonerMain.setPlacecou("");
                    prisonerMain.setPlacevill("");
                    prisonerMain.setPlacenum("");
                    prisonerMain.setArrestpro("");
                    prisonerMain.setArrestcity("");
                    prisonerMain.setArrestcou("");
                    prisonerMain.setArrestvill("");
                    prisonerMain.setArrestnum("");
                } else {
                    // 非大陆，设置逮捕机关地址
                    prisonerMain.setPriAddr(Constants.NumberStr.NUM_STR_ZERO_FOUR);
                    prisonerMain.setHjType(Constants.NumberStr.NUM_STR_ZERO_ONE);
                    String detailType = "";
                    if(Constants.NumberStr.NUM_STR_ZERO_FOUR.equals(priAddr)) {
                        detailType = Constants.NumberStr.NUM_STR_ONE;
                    } else if(Constants.NumberStr.NUM_STR_ZERO_FIVE.equals(priAddr)) {
                        detailType = Constants.NumberStr.NUM_STR_TWO;
                    } else if(Constants.NumberStr.NUM_STR_ZERO_SIX.equals(priAddr)) {
                        detailType = Constants.NumberStr.NUM_STR_THREE;
                    } else if(Constants.NumberStr.NUM_STR_ZERO_SEVEN.equals(priAddr)) {
                        detailType = Constants.NumberStr.NUM_STR_FOUR;
                    } else if(Constants.NumberStr.NUM_STR_ZERO_EIGHT.equals(priAddr)) {
                        detailType = Constants.NumberStr.NUM_STR_FIVE;
                    }
                    prisonerMain.setDetailType(detailType);
                    prisonerMain.setArrestpro(arrestpro);
                    prisonerMain.setArrestcity(arrestcity);
                    prisonerMain.setArrestcou(arrestcou);
                    prisonerMain.setArrestvill(arrestvill);
                    prisonerMain.setArrestnum(arrestnum);
                    prisonerMain.setNativepro("");
                    prisonerMain.setNativecity("");
                    prisonerMain.setNativecou("");
                    prisonerMain.setNativevill("");
                    prisonerMain.setNativenum("");
                    prisonerMain.setPlacepro("");
                    prisonerMain.setPlacecity("");
                    prisonerMain.setPlacecou("");
                    prisonerMain.setPlacevill("");
                    prisonerMain.setPlacenum("");
                    prisonerMain.setInvestigatePro("");
                    prisonerMain.setInvestigateCity("");
                    prisonerMain.setInvestigateCou("");
                    prisonerMain.setInvestigateVill("");
                    prisonerMain.setInvestigateNum("");
                }
            }
        }
        // 2、check多媒体表
        {
            for(UploadAppendixFiles uploadAppendixFiles : multimediaInfos) {
                // 校验
                String taskId = uploadAppendixFiles.getTaskId();
                String imgstr = uploadAppendixFiles.getImgstr();
                String filetype = uploadAppendixFiles.getFiletype();
                // 校验
                if(!imgs.contains("imgstr") && StringUtils.isEmpty(imgstr)) {
                    // errMessage.append("多媒体信息 图片base64编码不能为空。");
                    errCodes.add("200001");
                }
                if(!imgs.contains("taskId") && !Constants.NumberStr.NUM_STR_TWO.equals(taskId) && !Constants.NumberStr.NUM_STR_THREE.equals(taskId)) {
                    // errMessage.append("多媒体信息 文件标识只能为2(头像) 3(指纹)。");
                    errCodes.add("200002");
                }
                if(!imgs.contains("filetype") && StringUtils.isEmpty(filetype)) {
                    // errMessage.append(多媒体信息 文件后缀不能为空。");
                    errCodes.add("200003");
                }
                if(errCodes.isEmpty()) {
                    uploadAppendixFiles.setTaskId(taskId);
                }
            }
        }
        // 3、check服刑信息表
        {
            for(Map.Entry<String,Object> next : prisonerFxMap.entrySet()) {
                Object obj = next.getValue();
                if(obj instanceof String) {
                    next.setValue(((String)obj).trim());
                }
            }
            if(!prisonerFxMap.isEmpty()) {
                // 取出prisonerFxMap并校验
                String critype = (String)prisonerFxMap.get("critype");
                String fzlx = (String)prisonerFxMap.get("fzlx");
                String pritime = (String)prisonerFxMap.get("pritime");
                String arrJg = (String)prisonerFxMap.get("arrJg");
                String precri = (String)prisonerFxMap.get("precri");
                String canji = (String)prisonerFxMap.get("canji");
                String priBegin;
                if(prisonerFxMap.get("priBegin") instanceof Long) {
                    long priBeginL = (long)prisonerFxMap.get("priBegin");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    priBegin = sdf.format(new Date(priBeginL));
                } else {
                    priBegin = (String)prisonerFxMap.get("priBegin");
                }
                String priStop;
                if(prisonerFxMap.get("priStop") instanceof Long) {
                    long priStopL = (long)prisonerFxMap.get("priStop");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    priStop = sdf.format(new Date(priStopL));
                } else {
                    priStop = (String)prisonerFxMap.get("priStop");
                }
                // 判断服刑人员是否出狱,pri_begin必须大于等于2022-01-01 00:00:00并且pri_stop < 当前时间 - 15天
                if(null != priBegin) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        long time = sdf.parse(priBegin).getTime();
                        long time1 = sdf.parse("2020-01-01 00:00:00").getTime();
                        if(time < time1 && priBeginFlag) {
                            // 数据对接可以录入2020年之前的但是身份证、姓名不可重复、不许有重复的人员
                            errCodes.add("99997");
                        }
                    } catch(ParseException e) {
                        e.printStackTrace();
                    }
                }
                if(null != priStop) {
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar cal = Calendar.getInstance();
                    // 获取前面的时间用-负号
                    cal.setTime(date);
                    cal.add(Calendar.DAY_OF_MONTH,-15);
                    long time = cal.getTime().getTime();
                    // 获取刑期止日
                    try {
                        long time1 = sdf.parse(priStop).getTime();
                        if(time > time1 && priBeginFlag) {
                            // 刑期止日可以小于当前时间并且录入的姓名、身份证号不能有重复人员
                            errCodes.add("99998");
                        }
                    } catch(ParseException e) {
                        e.printStackTrace();
                    }
                }
                String addpenalty = (String)prisonerFxMap.get("addpenalty");
                String aftype = (String)prisonerFxMap.get("aftype");
                String bqzy = (String)prisonerFxMap.get("bqzy");
                String jinengtype = (String)prisonerFxMap.get("jinengtype");
                // 校验罪名
                if(!fxs.contains("critype") && StringUtils.isEmpty(critype)) {
                    // errMessage.append("服刑信息 罪名不能为空。");
                    errCodes.add("300001");
                }
                if(!StringUtils.isEmpty(critype)) {
                    String[] critypes = critype.split(",");
                    for(String a : critypes) {
                        if(!StrUtil.containsEquals(a,DICTIONARY.getaddpenalty())) {
                            if(stringRedisTemplate.hasKey("critypeCode")) {
                                String critypeCode = (String)stringRedisTemplate.opsForHash().get("critypeCode",a);
                                if(StringUtils.isEmpty(critypeCode)) {
                                    // errMessage.append("服刑信息 罪名不正确。");
                                    errCodes.add("300002");
                                }
                            } else {
                                // 从数据库中查询是否存在该罪名code
                                Map<String,String> map = new HashMap<>(16);
                                map.put("codeType",Constants.CodeType.CODE_ZMFL_DM);
                                map.put("codeId",a);
                                SystemCode codeByMap = systemCodeMapper.getCodeByMap(map);
                                if(null == codeByMap) {
                                    // errMessage.append("服刑信息 罪名不正确。");
                                    errCodes.add("300002");
                                }
                            }
                        }
                    }
                }
                // 校验犯罪类型
                if(!fxs.contains("fzlx") && StringUtils.isEmpty(fzlx)) {
                    // errMessage.append("服刑信息 犯罪类型不能为空。");
                    errCodes.add("300003");
                }
                if(!StringUtils.isEmpty(fzlx) && !StrUtil.contains(fzlx,DICTIONARY.getfzlx())) {
                    // errMessage.append("服刑信息 犯罪类型不正确。");
                    errCodes.add("300004");
                }
                // 校验现刑期
                if(!fxs.contains("pritime") && StringUtils.isEmpty(pritime)) {
                    // errMessage.append("服刑信息 现刑期不能为空。");
                    errCodes.add("300005");
                }
                if(!StringUtils.isEmpty(pritime) && !StrUtil.containsEquals(pritime,DICTIONARY.getpritime())) {
                    // errMessage.append("服刑信息 现刑期不正确。");
                    errCodes.add("300006");
                }
                // 校验逮捕机关
                if(!fxs.contains("arrJg") && StringUtils.isEmpty(arrJg)) {
                    // errMessage.append("服刑信息 逮捕机关不能为空。");
                    errCodes.add("300007");
                }
                if(!StringUtils.isEmpty(arrJg) && 50 < arrJg.length()) {
                    // errMessage.append("服刑信息 逮捕机关长度不能超过50。");
                    errCodes.add("300008");
                }
                // 校验是否累惯犯
                if(!fxs.contains("precri") && StringUtils.isEmpty(precri)) {
                    // errMessage.append("服刑信息 是否累惯犯不能为空。");
                    errCodes.add("300009");
                }
                if(!StringUtils.isEmpty(precri) && !StrUtil.contains(precri,DICTIONARY.getprecri())) {
                    // errMessage.append("服刑信息 是否累惯犯不正确。");
                    errCodes.add("300010");
                }
                // 校验是否疾病、残疾
                if(!fxs.contains("canji") && StringUtils.isEmpty(canji)) {
                    // errMessage.append("服刑信息 是否疾病、残疾不能为空。");
                    errCodes.add("300011");
                }
                if(!StringUtils.isEmpty(canji) && !StrUtil.containsEquals(canji,DICTIONARY.getcanji())) {
                    // errMessage.append("服刑信息 是否疾病、残疾不正确。");
                    errCodes.add("300012");
                }
                // 校验刑期起日
                if(!fxs.contains("priBegin") && StringUtils.isEmpty(priBegin)) {
                    // errMessage.append("服刑信息 刑期起日不能为空。");
                    errCodes.add("300013");
                }
                if(!StringUtils.isEmpty(priBegin) && DateUtil.checkStrDate(priBegin)) {
                    // errMessage.append("服刑信息 刑期起日不正确。");
                    errCodes.add("300014");
                }
                // 校验刑期止日
                if(!fxs.contains("priStop") && StringUtils.equals(pritime,"9999") && StringUtils.isEmpty(priStop)) {
                    // errMessage.append("服刑信息 刑期止日不能为空。");
                    errCodes.add("300015");
                }
                if(!StringUtils.isEmpty(priStop) && DateUtil.checkStrDate(priStop)) {
                    // errMessage.append("服刑信息 刑期止日不正确。");
                    errCodes.add("300016");
                }
                if(StringUtils.equals(pritime,"9999") && !StringUtils.isEmpty(priBegin) && !StringUtils.isEmpty(priStop) && 0 < priBegin.compareTo(priStop)) {
                    // errMessage.append("服刑信息 刑期起日不能大于刑期止日。");
                    errCodes.add("300017");
                }
                // 校验附加刑
                if(!fxs.contains("addpenalty") && StringUtils.isEmpty(addpenalty)) {
                    // errMessage.append("服刑信息 附加刑不能为空。");
                    errCodes.add("300018");
                }
                if(!StringUtils.isEmpty(addpenalty)) {
                    String[] addpenaltys = addpenalty.split(",");
                    for(String a : addpenaltys) {
                        if(!StrUtil.containsEquals(a,DICTIONARY.getaddpenalty())) {
                            // errMessage.append("服刑信息 附加刑不正确。");
                            errCodes.add("300019");
                            break;
                        }
                    }
                }
                // 校验案犯类别
                if(!fxs.contains("aftype") && StringUtils.isEmpty(aftype)) {
                    // errMessage.append("服刑信息 案犯类别不能为空。");
                    errCodes.add("300020");
                }
                if(!StringUtils.isEmpty(aftype) && !StrUtil.containsEquals(aftype,DICTIONARY.getaftype())) {
                    // errMessage.append("服刑信息 案犯类别不正确。");
                    errCodes.add("300021");
                }
                if(!fxs.contains("bqzy") && StringUtils.isEmpty(bqzy)) {
                    // errMessage.append("服刑信息 捕前职业不能为空。");
                    errCodes.add("300022");
                }
                // 校验捕前职业
                if(!fxs.contains("bqzy") && !StringUtils.isEmpty(bqzy)) {
                    if(stringRedisTemplate.hasKey("bqzy")) {
                        String bqzyCode = (String)stringRedisTemplate.opsForHash().get("bqzy",bqzy);
                        if(StringUtils.isEmpty(bqzyCode)) {
                            // errMessage.append("服刑信息 捕前职业不正确。");
                            errCodes.add("300023");
                        }
                    } else {
                        // 从数据库中查询是否存在该补前职业code
                        Map<String,String> map = new HashMap<>(16);
                        map.put("codeType",Constants.CodeType.CODE_ZY_DM);
                        map.put("codeId",bqzy);
                        SystemCode codeByMap = systemCodeMapper.getCodeByMap(map);
                        if(null == codeByMap) {
                            // errMessage.append("服刑信息 捕前职业不正确。");
                            errCodes.add("300023");
                        }
                    }
                }
                // 校验捕前职业分类
                if(!fxs.contains("jinengtype") && !StringUtils.isEmpty(jinengtype) && !StrUtil.contains(jinengtype,DICTIONARY.getjinengtype())) {
                    // errMessage.append("服刑信息 捕前职业分类不正确。");
                    errCodes.add("300024");
                }
                // 封装实体类
                if(errCodes.isEmpty()) {
                    String json = JSON.toJSONString(prisonerFxMap);
                    prisonerFx = JsonUtil.toBean(json,PrisonerFx.class);
                    if(!StringUtils.isEmpty(pritime) && StrUtil.containsEquals(pritime,DICTIONARY.getDeathpenalty())) {
                        prisonerFx.setPriStop(null);
                    }
                }
            }
        }
        // 4、check社会关系表
        {
            for(PrisonerSr p : prisonerSrs) {
                // 取出prisonerSrMap并校验
                String thename = p.getThename();
                String relation = p.getRelation();
                String idnumber = p.getIdnumber();
                Date age = p.getAge();
                String danwei = p.getDanwei();
                String tel = p.getTel();
                String mobile = p.getMobile();
                String addrpro = p.getAddrpro();
                //todo 针对于重庆的省直辖区县做单独处理，后续取消
                String addrcity = cityCheck(p.getAddrcity());
                String addrcou = p.getAddrcou();
                String addrvil = p.getAddrvil();
                String addrdetail = p.getAddrdetail();
                p.setAdduserid(userDTO.getDepartid());
                // 校验姓名
                if(!srs.contains("thename") && StringUtils.isEmpty(thename)) {
                    // errMessage.append("配偶、父母、社会关系 姓名不能为空。");
                    errCodes.add("400001");
                }
                if(!StringUtils.isEmpty(thename) && 30 < thename.length()) {
                    // errMessage.append("配偶、父母、社会关系 姓名长度不能超过30。");
                    errCodes.add("400002");
                }
                // 校验关系
                if(!StringUtils.isEmpty(relation) && !StrUtil.contains(relation,DICTIONARY.getrelation())) {
                    // errMessage.append("配偶、父母、社会关系 关系编码不正确。");
                    errCodes.add("400004");
                }
                // 校验身份证
                if(!srs.contains("idnumber") && !StringUtils.isEmpty(idnumber) && IdNumUtil.checkIdNum(idnumber)) {
                    // errMessage.append("配偶、父母、社会关系 身份证号码不正确。");
                    errCodes.add("400005");
                }
                // 校验单位
                if(!StringUtils.isEmpty(danwei) && 50 < danwei.length()) {
                    // errMessage.append("配偶、父母、社会关系 工作单位长度不能超过50。");
                    errCodes.add("400007");
                }
                // 校验出生日期
                if(null != age) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String str = sdf.format(age);
                    if(DateUtil.checkStrDate(str)) {
                        // errMessage.append("配偶、父母、社会关系 出生日期不正确。");
                        errCodes.add("400008");
                    }
                }
                // 校验电话
                // 固定电话
                if(!srs.contains("tel") && !StringUtils.isEmpty(tel)) {
                    if(!PhoneUtil.phone(tel)) {
                        // errMessage.append("配偶、父母、社会关系 固定电话不正确。");
                        errCodes.add("400010");
                    }
                }
                // 手机号校验
                if(!srs.contains("mobile") && !StringUtils.isEmpty(mobile)) {
                    if(!PhoneUtil.isMobile(mobile)) {
                        // errMessage.append("配偶、父母、社会关系 手机号码不正确。");
                        errCodes.add("400011");
                    }
                }
                // 校验地址
                boolean addrproErrFlag = false;
                boolean addrcityErrFlag = false;
                boolean addrcouErrFlag = false;
                boolean addrvillErrFlag = false;
                if(!StringUtils.isEmpty(addrpro)) {
                    String pCodePro = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",addrpro);
                    if(!srs.contains("addrpro") && !Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                        // errMessage.append("配偶、父母、社会关系 家庭住址编码不正确。");
                        errCodes.add("400016");
                    } else if(srs.contains("addrpro") && !Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                        addrproErrFlag = true;
                    } else {
                        if(!StringUtils.isEmpty(addrcity)) {
                            String pCodeCity = (String)stringRedisTemplate.opsForHash()
                                                                          .get("areaCodeAndPcode",addrcity);
                            if(!srs.contains("addrcity") && !addrpro.equals(pCodeCity)) {
                                // errMessage.append("配偶、父母、社会关系 家庭住址编码不正确。");
                                errCodes.add("400016");
                            } else if(srs.contains("addrcity") && !addrpro.equals(pCodeCity)) {
                                addrcityErrFlag = true;
                            } else {
                                if(!StringUtils.isEmpty(addrcou)) {
                                    String pCodeCou = (String)stringRedisTemplate.opsForHash()
                                                                                 .get("areaCodeAndPcode",addrcou);
                                    if(!srs.contains("addrcou") && !addrcity.equals(pCodeCou)) {
                                        // errMessage.append("配偶、父母、社会关系 家庭住址编码不正确。");
                                        errCodes.add("400016");
                                    } else if(srs.contains("addrcou") && !addrcity.equals(pCodeCou)) {
                                        addrcouErrFlag = true;
                                    } else {
                                        if(!StringUtils.isEmpty(addrvil)) {
                                            String pCodeVill = (String)stringRedisTemplate.opsForHash()
                                                                                          .get("areaCodeAndPcode",addrvil);
                                            if(!srs.contains("addrvill") && !addrcou.equals(pCodeVill)) {
                                                // errMessage.append("配偶、父母、社会关系 家庭住址编码不正确。");
                                                errCodes.add("400016");
                                            } else if(srs.contains("addrvill") && !addrcou.equals(pCodeVill)) {
                                                addrvillErrFlag = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(!srs.contains("addrdetail")) {
                    if(!StringUtils.isEmpty(addrdetail) && 50 < addrdetail.length()) {
                        // errMessage.append("配偶、父母、社会关系 家庭住址详细信息长度不能超过50。");
                        errCodes.add("400018");
                    }
                }
                // 封装实体类
                if(errCodes.isEmpty()) {
                    if(addrproErrFlag) {
                        p.setAddrpro("");
                        p.setAddrcity("");
                        p.setAddrcou("");
                        p.setAddrvil("");
                    } else if(addrcityErrFlag) {
                        p.setAddrcity("");
                        p.setAddrcou("");
                        p.setAddrvil("");
                    } else if(addrcouErrFlag) {
                        p.setAddrcou("");
                        p.setAddrvil("");
                    } else if(addrvillErrFlag) {
                        p.setAddrvil("");
                    }
                    if(!StringUtils.isEmpty(idnumber) && 18 == idnumber.length()) {
                        // 身份证不为空，并且为18位身份证，设置生日为身份证的7～14位
                        String year = idnumber.substring(6,10);
                        String month = idnumber.substring(10,12);
                        String day = idnumber.substring(12,14);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date birthday = null;
                        try {
                            // 注意格式需要与上面一致，不然会出现异常
                            birthday = sdf.parse(new StringBuffer(year).append("-").append(month).append("-")
                                                                       .append(day).toString());
                        } catch(ParseException e) {
                            log.error("发生异常:",e);
                        }
                        p.setAge(birthday);
                    }
                    // 拼接手机号
                    StringBuilder sb = new StringBuilder(16);
                    if(!StringUtils.isEmpty(tel)) {
                        sb.append(tel);
                    }
                    sb.append("|");
                    if(!StringUtils.isEmpty(mobile)) {
                        sb.append(mobile);
                    }
                    p.setTel(sb.toString());
                }
            }
        }
        // 5、check子女表
        {
            for(PrisonerZn prisonerZn1 : prisonerZns) {
                // 取出prisonerZnMap并校验
                String name = prisonerZn1.getName();
                String sex = prisonerZn1.getSex();
                String znsfId = prisonerZn1.getZnsfId();
                Date age = prisonerZn1.getAge();
                String jianhuren = prisonerZn1.getJianhuren();
                String kunnan = prisonerZn1.getKunnan();
                String shixue = prisonerZn1.getShixue();
                String liulang = prisonerZn1.getLiulang();
                String fanzui = prisonerZn1.getFanzui();
                String nativepro = prisonerZn1.getNativepro();
                String nativecity = prisonerZn1.getNativecity();
                String nativecou = prisonerZn1.getNativecou();
                String nativevill = prisonerZn1.getNativevill();
                String nativenum = prisonerZn1.getNativenum();
                String placepro = prisonerZn1.getPlacepro();
                String placecity = prisonerZn1.getPlacecity();
                String placecou = prisonerZn1.getPlacecou();
                String placevill = prisonerZn1.getPlacevill();
                String placenum = prisonerZn1.getPlacenum();
                prisonerZn1.setAdduserid(userDTO.getDepartid());
                // 校验姓名
                if(!zns.contains("name") && StringUtils.isEmpty(name)) {
                    // errMessage.append("子女 姓名不能为空。");
                    errCodes.add("500001");
                }
                if(!StringUtils.isEmpty(name) && 30 < name.length()) {
                    // errMessage.append("子女 姓名长度不能超过30。");
                    errCodes.add("500002");
                }
                // 校验性别
                if(!StringUtils.isEmpty(sex) && !StrUtil.containsEquals(sex,DICTIONARY.getsex())) {
                    // errMessage.append("子女 性别不正确。");
                    errCodes.add("500004");
                }
                // 校验身份证、年龄
                if(!zns.contains("znsfId")) {
                    if(!StringUtils.isEmpty(znsfId) && IdNumUtil.checkIdNum(znsfId)) {
                        // errMessage.append("子女 身份证号码不正确。");
                        errCodes.add("500006");
                    }
                }
                // 校验监护人情况
                if(!StringUtils.isEmpty(jianhuren) && !StrUtil.containsEquals(jianhuren,DICTIONARY.getjianhuren())) {
                    // errMessage.append("子女 监护人情况不正确。");
                    errCodes.add("500008");
                }
                // 校验生活困难程度
                if(!StringUtils.isEmpty(kunnan) && !StrUtil.containsEquals(kunnan,DICTIONARY.getkunnan())) {
                    // errMessage.append("子女 生活困难程度不正确。");
                    errCodes.add("500010");
                }
                // 校验是否失学
                if(!StringUtils.isEmpty(shixue) && !StrUtil.containsEquals(shixue,DICTIONARY.getshixue())) {
                    // errMessage.append("子女 是否失学不正确。");
                    errCodes.add("500012");
                }
                // 校验是否流浪社会
                if(!StringUtils.isEmpty(liulang) && !StrUtil.containsEquals(liulang,DICTIONARY.getliulang())) {
                    // errMessage.append("子女 是否流浪社会不正确。");
                    errCodes.add("500014");
                }
                // 校验有无违法犯罪行为
                if(!StringUtils.isEmpty(fanzui) && !StrUtil.containsEquals(fanzui,DICTIONARY.getfanzui())) {
                    // errMessage.append("子女 有无违法犯罪行为不正确。");
                    errCodes.add("500016");
                }
                // 校验户籍地址
                if(!StringUtils.isEmpty(nativepro)) {
                    String pCodePro = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",nativepro);
                    if(!Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                        // errMessage.append("子女 户籍地址编码不正确。");
                        errCodes.add("500021");
                    } else {
                        if(!StringUtils.isEmpty(nativecity)) {
                            String pCodeCity = (String)stringRedisTemplate.opsForHash()
                                                                          .get("areaCodeAndPcode",nativecity);
                            if(!nativepro.equals(pCodeCity)) {
                                // errMessage.append("子女 户籍地址编码不正确。");
                                errCodes.add("500021");
                            } else {
                                if(!StringUtils.isEmpty(nativecou)) {
                                    String pCodeCou = (String)stringRedisTemplate.opsForHash()
                                                                                 .get("areaCodeAndPcode",nativecou);
                                    if(!nativecity.equals(pCodeCou)) {
                                        // errMessage.append("子女 户籍地址编码不正确。");
                                        errCodes.add("500021");
                                    } else {
                                        if(!StringUtils.isEmpty(nativevill)) {
                                            String pCodeVill = (String)stringRedisTemplate.opsForHash()
                                                                                          .get("areaCodeAndPcode",nativevill);
                                            if(!nativecou.equals(pCodeVill)) {
                                                // errMessage.append("子女 户籍地址编码不正确。");
                                                errCodes.add("500021");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(!StringUtils.isEmpty(nativenum) && 50 < nativenum.length()) {
                    // errMessage.append("子女 户籍详细信息长度不能超过50。");
                    errCodes.add("500023");
                }
                // 校验居住地址
                if(!StringUtils.isEmpty(placepro)) {
                    String pCodePro = (String)stringRedisTemplate.opsForHash().get("areaCodeAndPcode",placepro);
                    if(!Constants.NumberStr.NUM_STR_FU_ONE.equals(pCodePro)) {
                        // errMessage.append("子女 居住地址编码不正确。");
                        errCodes.add("500028");
                    } else {
                        if(!StringUtils.isEmpty(placecity)) {
                            String pCodeCity = (String)stringRedisTemplate.opsForHash()
                                                                          .get("areaCodeAndPcode",placecity);
                            if(!placepro.equals(pCodeCity)) {
                                // errMessage.append("子女 居住地址编码不正确。");
                                errCodes.add("500028");
                            } else {
                                if(!StringUtils.isEmpty(placecou)) {
                                    String pCodeCou = (String)stringRedisTemplate.opsForHash()
                                                                                 .get("areaCodeAndPcode",placecou);
                                    if(!placecity.equals(pCodeCou)) {
                                        // errMessage.append("子女 居住地址编码不正确。");
                                        errCodes.add("500028");
                                    } else {
                                        if(!StringUtils.isEmpty(placevill)) {
                                            String pCodeVill = (String)stringRedisTemplate.opsForHash()
                                                                                          .get("areaCodeAndPcode",placevill);
                                            if(!placecou.equals(pCodeVill)) {
                                                // errMessage.append("子女 居住地址编码不正确。");
                                                errCodes.add("500028");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(!StringUtils.isEmpty(placenum) && 50 < placenum.length()) {
                    // errMessage.append("子女 居住地址详细信息长度不能超过50。");
                    errCodes.add("500030");
                }
                // 封装实体类
                if(errCodes.isEmpty()) {
                    if(!StringUtils.isEmpty(znsfId) && 18 == znsfId.length() && null == age) {
                        // 身份证不为空，并且为18位身份证，设置生日为身份证的7～14位
                        String year = znsfId.substring(6,10);
                        String month = znsfId.substring(10,12);
                        String day = znsfId.substring(12,14);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date birthday = null;
                        try {
                            // 注意格式需要与上面一致，不然会出现异常
                            birthday = sdf.parse(new StringBuffer(year).append("-").append(month).append("-")
                                                                       .append(day).toString());
                        } catch(ParseException e) {
                            log.error("发生异常:",e);
                        }
                        prisonerZn1.setAge(birthday);
                    }
                }
            }
        }
        // 7、封装返回结果
        if(!errCodes.isEmpty()) {
            result.put("err",true);
            result.put("result",errCodes);
        } else {
            result.put("err",false);
            result.put("PrisonerMain",prisonerMain);
            result.put("MultimediaInfo",multimediaInfos);
            result.put("PrisonerFx",prisonerFx);
            result.put("PrisonerSr",prisonerSrs);
            result.put("PrisonerZn",prisonerZns);
            result.put("user",userDTO);
        }
        // log.info("预安置人员信息录入【校验耗时】:{} ms",System.currentTimeMillis() - start);
        return result;
    }

    /**
     * 3、组装数据
     * @param user user
     * @param prisonerMain prisonerMain
     * @param uploadAppendixFiles uploadAppendixFiles
     * @param prisonerFx prisonerFx
     * @param prisonerSrs prisonerSrs
     * @param prisonerZns prisonerZns
     * @param p p
     */
    private void assembled(UserInterFaceEntity user,PrisonerMain prisonerMain,List<UploadAppendixFiles> uploadAppendixFiles,PrisonerFx prisonerFx,List<PrisonerSr> prisonerSrs,List<PrisonerZn> prisonerZns,PrisaveTemp p) {
        // 1、定义返回串
        // 2、取出忽略字段（忽略字段在数据库表tbsys_interface_user表的unCheckField字段配置）
        // 用于控制各省不同监狱、社区矫正、看守所不同的参数空的配置。
        String unCheckField = user.getUnCheckField();
        String[] strs = unCheckField.split("\\|");
        Date date = new Date();
        List<String> mains = Arrays.asList(strs[0].split(","));
        List<String> imgs = Arrays.asList(strs[1].split(","));
        List<String> fxs = Arrays.asList(strs[2].split(","));
        List<String> srs = Arrays.asList(strs[3].split(","));
        List<String> zns = Arrays.asList(strs[4].split(","));
        // 3、封装
        long start = System.currentTimeMillis();
        // 3.01、封装状态表
        p.setId(IdGen.strid());
        p.setCreateUser(user.getAccount());
        p.setCreateTime(date);
        p.setUpdateUser(user.getAccount());
        p.setUpdateTime(date);
        // 3.1、封装主表
        int count1 = prisonerMainMapper.getRepeatJbxx(prisonerMain.getPriNum());
        if(Constants.Number.NUM_ZERO != count1) {
            throw new RuntimeException("安置帮教系统中存在该犯罪编号的基本信息");
        }
        prisonerMain.setId(IdGen.strid());
        // 取出监狱部门ID
        String departId = user.getDepartid();
        prisonerMain.setAdduserid(departId);
        if(null == prisonerMain.getUsedName() || "".equals(prisonerMain.getUsedName())) {
            prisonerMain.setUsedName("无");
        }
        prisonerMain.setAddusername(user.getUsername());
        prisonerMain.setPtype(user.getLevel());
        prisonerMain.setPrisonFather(user.getOrgid());
        prisonerMain.setPdanwei(user.getDepartid());
        prisonerMain.setPdanweiName(user.getDepartName());
        String idNum = prisonerMain.getIdNum();
        if(StringUtils.isNotBlank(idNum)) {
            prisonerMain.setIdNum(Sm4.encryptEcb(idNum));
        } else {
            prisonerMain.setIdNum(Sm4.encryptEcb(Constants.StrFinalValue.WU));
        }
        prisonerMain.setCreateUser(user.getAccount());
        prisonerMain.setCreateTime(date);
        prisonerMain.setUpdateUser(user.getAccount());
        prisonerMain.setUpdateTime(date);
        if(Constants.OrgLevel.LEVEL_KSS.equals(user.getLevel())) {
            //看守所录入
            prisonerMain.setPstate(Constants.InputEspecially.INPUT_KSS_INTERFACE);
        }
        if(Constants.OrgLevel.LEVEL_JY.equals(user.getLevel())) {
            //监狱录入
            prisonerMain.setPstate(Constants.InputEspecially.INPUT_JY_INTERFACE);
        }
        if(Constants.OrgLevel.LEVEL_SJZX.equals(user.getLevel())) {
            //社娇录入
            prisonerMain.setPstate(Constants.InputEspecially.INPUT_SJ_INTERFACE);
        }
        if(!StringUtils.isEmpty(prisonerMain.getNativepro())) {
            String nativeProName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getNativepro());
            nativeProName = StringUtils.isEmpty(nativeProName) ? systemCodeMapper.getNameByCode(prisonerMain.getNativepro()) : nativeProName;
            prisonerMain.setNativeproName(nativeProName);
        } else {
            prisonerMain.setNativeproName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getNativecity())) {
            String nativeCityName = (String)stringRedisTemplate.opsForHash()
                                                               .get("areaCode",prisonerMain.getNativecity());
            nativeCityName = StringUtils.isEmpty(nativeCityName) ? systemCodeMapper.getNameByCode(prisonerMain.getNativecity()) : nativeCityName;
            prisonerMain.setNativecityName(nativeCityName);
        } else {
            prisonerMain.setNativecityName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getNativecou())) {
            String nativeCouName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getNativecou());
            nativeCouName = StringUtils.isEmpty(nativeCouName) ? systemCodeMapper.getNameByCode(prisonerMain.getNativecou()) : nativeCouName;
            prisonerMain.setNativecouName(nativeCouName);
        } else {
            prisonerMain.setNativecouName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getNativevill())) {
            String nativeVillName = (String)stringRedisTemplate.opsForHash()
                                                               .get("areaCode",prisonerMain.getNativevill());
            nativeVillName = StringUtils.isEmpty(nativeVillName) ? systemCodeMapper.getNameByCode(prisonerMain.getNativevill()) : nativeVillName;
            prisonerMain.setNativevillName(nativeVillName);
        } else {
            prisonerMain.setNativevillName("");
        }
        // 查不清人员
        if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getHjType())) {
            if(!StringUtils.isEmpty(prisonerMain.getInvestigatePro())) {
                String investigateProName = (String)stringRedisTemplate.opsForHash()
                                                                       .get("areaCode",prisonerMain.getInvestigatePro());
                investigateProName = StringUtils.isEmpty(investigateProName) ? systemCodeMapper.getNameByCode(prisonerMain.getInvestigatePro()) : investigateProName;
                prisonerMain.setInvestigateProName(investigateProName);
            } else {
                prisonerMain.setInvestigateProName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateCity())) {
                String investigateCityName = (String)stringRedisTemplate.opsForHash()
                                                                        .get("areaCode",prisonerMain.getInvestigateCity());
                investigateCityName = StringUtils.isEmpty(investigateCityName) ? systemCodeMapper.getNameByCode(prisonerMain.getInvestigateCity()) : investigateCityName;
                prisonerMain.setInvestigateCityName(investigateCityName);
            } else {
                prisonerMain.setInvestigateCityName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateCou())) {
                String investigateCouName = (String)stringRedisTemplate.opsForHash()
                                                                       .get("areaCode",prisonerMain.getInvestigateCou());
                investigateCouName = StringUtils.isEmpty(investigateCouName) ? systemCodeMapper.getNameByCode(prisonerMain.getInvestigateCou()) : investigateCouName;
                prisonerMain.setInvestigateCouName(investigateCouName);
            } else {
                prisonerMain.setInvestigateCouName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String investigateVillName = (String)stringRedisTemplate.opsForHash()
                                                                        .get("areaCode",prisonerMain.getInvestigateVill());
                investigateVillName = StringUtils.isEmpty(investigateVillName) ? systemCodeMapper.getNameByCode(prisonerMain.getInvestigateVill()) : investigateVillName;
                prisonerMain.setInvestigateVillName(investigateVillName);
            } else {
                prisonerMain.setInvestigateVillName("");
            }
        }
        // 非大陆户籍
        if(StrUtil.containsEquals(prisonerMain.getPriAddr(),DICTIONARY.getfdlpriaddr())) {
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String arrestProName = (String)stringRedisTemplate.opsForHash()
                                                                  .get("areaCode",prisonerMain.getArrestpro());
                arrestProName = StringUtils.isEmpty(arrestProName) ? systemCodeMapper.getNameByCode(prisonerMain.getArrestpro()) : arrestProName;
                prisonerMain.setArrestproName(arrestProName);
            } else {
                prisonerMain.setArrestproName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String arrestCityName = (String)stringRedisTemplate.opsForHash()
                                                                   .get("areaCode",prisonerMain.getArrestcity());
                arrestCityName = StringUtils.isEmpty(arrestCityName) ? systemCodeMapper.getNameByCode(prisonerMain.getArrestcity()) : arrestCityName;
                prisonerMain.setArrestcityName(arrestCityName);
            } else {
                prisonerMain.setArrestcityName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String arrestCouName = (String)stringRedisTemplate.opsForHash()
                                                                  .get("areaCode",prisonerMain.getArrestcou());
                arrestCouName = StringUtils.isEmpty(arrestCouName) ? systemCodeMapper.getNameByCode(prisonerMain.getArrestcou()) : arrestCouName;
                prisonerMain.setArrestcouName(arrestCouName);
            } else {
                prisonerMain.setArrestcouName("");
            }
            if(!StringUtils.isEmpty(prisonerMain.getInvestigateVill())) {
                String arrestVillName = (String)stringRedisTemplate.opsForHash()
                                                                   .get("areaCode",prisonerMain.getArrestvill());
                arrestVillName = StringUtils.isEmpty(arrestVillName) ? systemCodeMapper.getNameByCode(prisonerMain.getArrestvill()) : arrestVillName;
                prisonerMain.setArrestvillName(arrestVillName);
            } else {
                prisonerMain.setArrestvillName("");
            }
        }
        // 若居住省市县街道编码不为空,则根据redis中行政区划数据获取对应的中文
        if(!StringUtils.isEmpty(prisonerMain.getPlacepro())) {
            String placeProName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getPlacepro());
            placeProName = StringUtils.isEmpty(placeProName) ? systemCodeMapper.getNameByCode(prisonerMain.getPlacepro()) : placeProName;
            prisonerMain.setPlaceproName(placeProName);
        } else {
            prisonerMain.setPlaceproName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getPlacecity())) {
            String placeCityName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getPlacecity());
            placeCityName = StringUtils.isEmpty(placeCityName) ? systemCodeMapper.getNameByCode(prisonerMain.getPlacecity()) : placeCityName;
            prisonerMain.setPlacecityName(placeCityName);
        } else {
            prisonerMain.setPlacecityName("");
        }
        if(null != prisonerMain.getPlacecou()) {
            String placeCouName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getPlacecou());
            placeCouName = StringUtils.isEmpty(placeCouName) ? systemCodeMapper.getNameByCode(prisonerMain.getPlacecou()) : placeCouName;
            prisonerMain.setPlacecouName(placeCouName);
        } else {
            prisonerMain.setPlacecouName("");
        }
        if(!StringUtils.isEmpty(prisonerMain.getPlacevill())) {
            String placevillName = (String)stringRedisTemplate.opsForHash().get("areaCode",prisonerMain.getPlacevill());
            placevillName = StringUtils.isEmpty(placevillName) ? systemCodeMapper.getNameByCode(prisonerMain.getPlacevill()) : placevillName;
            prisonerMain.setPlacevillName(placevillName);
        } else {
            prisonerMain.setPlacevillName("");
        }
        prisonerMain.setState(Constants.NumberStr.NUM_STR_ZERO);
        boolean mainFlag = false;
        boolean fxFlag = false;
        if(StringUtils.isNotEmpty(prisonerMain.getPName()) && StringUtils.isNotEmpty(prisonerMain.getSex()) && StringUtils.isNotEmpty(prisonerMain.getNationality()) && StringUtils.isNotEmpty(prisonerMain.getIdType()) && null != prisonerMain.getAddtime() && StringUtils.isNotEmpty(prisonerMain.getEducation()) && StringUtils.isNotEmpty(prisonerMain.getPriAddr())) {
            //如果户籍为完整并且农村和城镇
            boolean flag = (Constants.NumberStr.NUM_STR_ZERO_ONE.equals(prisonerMain.getPriAddr()) || Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getPriAddr())) && Constants.NumberStr.NUM_STR_ZERO_ONE.equals(prisonerMain.getHjType());
            if(flag) {
                if(StringUtils.isNotEmpty(prisonerMain.getNativepro()) && StringUtils.isNotEmpty(prisonerMain.getNativecity()) && StringUtils.isNotEmpty(prisonerMain.getNativecou()) && StringUtils.isNotEmpty(prisonerMain.getNativenum())) {
                    p.setMainFlag(Constants.Number.NUM_ONE);
                    mainFlag = true;
                }
            } else if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getHjType())) {
                //如果户籍为查不清人员
                if(StringUtils.isNotEmpty(prisonerMain.getInvestigatePro()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateCity()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateCou()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateVill()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateNum())) {
                    p.setMainFlag(Constants.Number.NUM_ONE);
                    mainFlag = true;
                }
            } else {
                //如果户籍为完整并且非大陆
                if(StringUtils.isNotEmpty(prisonerMain.getArrestpro()) && StringUtils.isNotEmpty(prisonerMain.getArrestcity()) && StringUtils.isNotEmpty(prisonerMain.getArrestcou()) && StringUtils.isNotEmpty(prisonerMain.getArrestvill()) && StringUtils.isNotEmpty(prisonerMain.getArrestnum())) {
                    p.setMainFlag(Constants.Number.NUM_ONE);
                    mainFlag = true;
                }
            }
        }
        // 3.2、封装多媒体表
        for(UploadAppendixFiles uploadAppendixFile : uploadAppendixFiles) {
            uploadAppendixFile.setId(prisonerMain.getId());
            uploadAppendixFile.setSingleId(com.sinog.core.utilbean.IdGen.strid());
            uploadAppendixFile.setAccount(user.getAccount());
            uploadAppendixFile.setUsername(user.getUsername());
            uploadAppendixFile.setUploadDate(date);
            p.setZzFlag(Constants.Number.NUM_ONE);
        }
        // 3.3、封装服刑表
        int count3 = prisonerFxMapper.getRepeatFxxx(prisonerFx.getPriNum());
        if(Constants.Number.NUM_ZERO != count3) {
            throw new RuntimeException("安置帮教系统中存在该犯罪编号的服刑信息");
        }
        prisonerFx.setId(IdGen.strid());
        prisonerFx.setAdduserid(departId);
        prisonerFx.setCreateUser(user.getAccount());
        prisonerFx.setCreateTime(date);
        prisonerFx.setUpdateUser(user.getAccount());
        prisonerFx.setUpdateTime(date);
        if(StringUtils.isNotEmpty(prisonerFx.getCritype()) && StringUtils.isNotEmpty(prisonerFx.getPritime()) && StringUtils.isNotEmpty(prisonerFx.getArrJg()) && StringUtils.isNotEmpty(prisonerFx.getPrecri()) && StringUtils.isNotEmpty(prisonerFx.getCanji()) && null != prisonerFx.getPriBegin() && null != prisonerFx.getPriStop() && StringUtils.isNotEmpty(prisonerFx.getAddpenalty()) && StringUtils.isNotEmpty(prisonerFx.getAftype()) && StringUtils.isNotEmpty(prisonerFx.getBqzy())) {
            p.setFxFlag(Constants.Number.NUM_ONE);
            fxFlag = true;
        }
        if(mainFlag && fxFlag) {
            p.setSrFlag(Constants.Number.NUM_ONE);
            p.setZzFlag(Constants.Number.NUM_ONE);
        }
        // 3.4、封装社会关系表
        for(PrisonerSr prisonerSr : prisonerSrs) {
            prisonerSr.setId(IdGen.strid());
            prisonerSr.setAdduserid(departId);
            prisonerSr.setCreateUser(user.getAccount());
            prisonerSr.setCreateTime(date);
            prisonerSr.setUpdateUser(user.getAccount());
            prisonerSr.setUpdateTime(date);
            String idType = prisonerSr.getIdType();
            String idNumber = prisonerSr.getIdnumber();
            // idType="98"为其他证件,idType为null则默认给"98"
            if(StringUtils.isBlank(idType)) {
                prisonerSr.setIdType(Constants.NumberStr.NUM_STR_NINE_EIGHT);
            } else {
                prisonerSr.setIdType(idType);
            }
            if(StringUtils.isNotBlank(idNumber)) {
                // Sm4.encryptEcb(idNumber) 加密存储数据库
                prisonerSr.setIdnumber(Sm4.encryptEcb(idNumber));
            } else {
                prisonerSr.setIdnumber(Sm4.encryptEcb(Constants.StrFinalValue.WU));
            }
            // 是否忽略填充省市县街道名称，有些客户对接客户端不能提供省市县编码，则不填充
            if(!srs.contains("ssxjd")) {
                if(!StringUtils.isEmpty(prisonerSr.getAddrpro())) {
                    String addrproname = (String)stringRedisTemplate.opsForHash()
                                                                    .get("areaCode",prisonerSr.getAddrpro());
                    addrproname = StringUtils.isEmpty(addrproname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrpro()) : addrproname;
                    prisonerSr.setAddrproname(addrproname);
                } else {
                    prisonerSr.setAddrproname("");
                }
                if(!StringUtils.isEmpty(prisonerSr.getAddrcity())) {
                    String addrcityname = (String)stringRedisTemplate.opsForHash()
                                                                     .get("areaCode",prisonerSr.getAddrcity());
                    addrcityname = StringUtils.isEmpty(addrcityname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrcity()) : addrcityname;
                    prisonerSr.setAddrcityname(addrcityname);
                } else {
                    prisonerSr.setAddrcityname("");
                }
                if(!StringUtils.isEmpty(prisonerSr.getAddrcou())) {
                    String addrcouname = (String)stringRedisTemplate.opsForHash()
                                                                    .get("areaCode",prisonerSr.getAddrcou());
                    addrcouname = StringUtils.isEmpty(addrcouname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrcou()) : addrcouname;
                    prisonerSr.setAddrcouname(addrcouname);
                } else {
                    prisonerSr.setAddrcouname("");
                }
                if(!StringUtils.isEmpty(prisonerSr.getAddrvil())) {
                    String addrvilname = (String)stringRedisTemplate.opsForHash()
                                                                    .get("areaCode",prisonerSr.getAddrvil());
                    addrvilname = StringUtils.isEmpty(addrvilname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrvil()) : addrvilname;
                    prisonerSr.setAddrvilname(addrvilname);
                } else {
                    prisonerSr.setAddrvilname("");
                }
                String addr = new StringBuilder(16).append(prisonerSr.getAddrproname())
                                                   .append(prisonerSr.getAddrcityname())
                                                   .append(prisonerSr.getAddrcouname())
                                                   .append(prisonerSr.getAddrvilname())
                                                   .append(prisonerSr.getAddrdetail()).toString();
                prisonerSr.setAddr(addr);
            } else {
                prisonerSr.setAddr(prisonerSr.getAddrdetail());
            }
            p.setSrFlag(Constants.Number.NUM_ONE);
        }
        // 3.5、封装子女表
        for(PrisonerZn prisonerZn : prisonerZns) {
            prisonerZn.setId(IdGen.strid());
            prisonerZn.setAdduserid(departId);
            prisonerZn.setCreateUser(user.getAccount());
            prisonerZn.setCreateTime(date);
            prisonerZn.setUpdateUser(user.getAccount());
            prisonerZn.setUpdateTime(date);
            String idType = prisonerZn.getIdType();
            String znsfId = prisonerZn.getZnsfId();
            // idType="98"为其他证件,idType为null则默认给"98"
            if(StringUtils.isNotBlank(idType)) {
                prisonerZn.setIdType(Constants.NumberStr.NUM_STR_NINE_EIGHT);
            } else {
                prisonerZn.setIdType(idType);
            }
            if(StringUtils.isNotBlank(znsfId)) {
                prisonerZn.setZnsfId(Sm4.encryptEcb(znsfId));
            } else {
                prisonerZn.setZnsfId(Sm4.encryptEcb(Constants.StrFinalValue.WU));
            }
            if(!zns.contains("ssxjd")) {
                if(!StringUtils.isEmpty(prisonerZn.getNativepro())) {
                    String nativeproName = (String)stringRedisTemplate.opsForHash()
                                                                      .get("areaCode",prisonerZn.getNativepro());
                    nativeproName = StringUtils.isEmpty(nativeproName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativepro()) : nativeproName;
                    prisonerZn.setNativeproName(nativeproName);
                } else {
                    prisonerZn.setNativeproName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getNativecity())) {
                    String nativecityName = (String)stringRedisTemplate.opsForHash()
                                                                       .get("areaCode",prisonerZn.getNativecity());
                    nativecityName = StringUtils.isEmpty(nativecityName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativecity()) : nativecityName;
                    prisonerZn.setNativecityName(nativecityName);
                } else {
                    prisonerZn.setNativecityName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getNativecou())) {
                    String nativecouName = (String)stringRedisTemplate.opsForHash()
                                                                      .get("areaCode",prisonerZn.getNativecou());
                    nativecouName = StringUtils.isEmpty(nativecouName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativecou()) : nativecouName;
                    prisonerZn.setNativecouName(nativecouName);
                } else {
                    prisonerZn.setNativecouName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getNativevill())) {
                    String nativevillName = (String)stringRedisTemplate.opsForHash()
                                                                       .get("areaCode",prisonerZn.getNativevill());
                    nativevillName = StringUtils.isEmpty(nativevillName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativevill()) : nativevillName;
                    prisonerZn.setNativevillName(nativevillName);
                } else {
                    prisonerZn.setNativevillName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getPlacepro())) {
                    String placeproName = (String)stringRedisTemplate.opsForHash()
                                                                     .get("areaCode",prisonerZn.getPlacepro());
                    placeproName = StringUtils.isEmpty(placeproName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacepro()) : placeproName;
                    prisonerZn.setPlaceproName(placeproName);
                } else {
                    prisonerZn.setPlaceproName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getPlacecity())) {
                    String placecityName = (String)stringRedisTemplate.opsForHash()
                                                                      .get("areaCode",prisonerZn.getPlacecity());
                    placecityName = StringUtils.isEmpty(placecityName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacecity()) : placecityName;
                    prisonerZn.setPlacecityName(placecityName);
                } else {
                    prisonerZn.setPlacecityName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getPlacecou())) {
                    String placecouName = (String)stringRedisTemplate.opsForHash()
                                                                     .get("areaCode",prisonerZn.getPlacecou());
                    placecouName = StringUtils.isEmpty(placecouName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacecou()) : placecouName;
                    prisonerZn.setPlacecouName(placecouName);
                } else {
                    prisonerZn.setPlacecouName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getPlacevill())) {
                    String placevillName = (String)stringRedisTemplate.opsForHash()
                                                                      .get("areaCode",prisonerZn.getPlacevill());
                    placevillName = StringUtils.isEmpty(placevillName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacevill()) : placevillName;
                    prisonerZn.setPlacevillName(placevillName);
                } else {
                    prisonerZn.setPlacevillName("");
                }
                String hujidi = new StringBuilder(16).append(prisonerZn.getNativeproName())
                                                     .append(prisonerZn.getNativecityName())
                                                     .append(prisonerZn.getNativecouName())
                                                     .append(prisonerZn.getNativevillName())
                                                     .append(prisonerZn.getNativenum()).toString();
                prisonerZn.setHujidi(hujidi);
                String juzhudi = new StringBuilder(16).append(prisonerZn.getPlaceproName())
                                                      .append(prisonerZn.getPlacecityName())
                                                      .append(prisonerZn.getPlacecouName())
                                                      .append(prisonerZn.getPlacevillName())
                                                      .append(prisonerZn.getPlacenum()).toString();
                prisonerZn.setJuzhudi(juzhudi);
            } else {
                prisonerZn.setHujidi(prisonerZn.getNativenum());
                prisonerZn.setJuzhudi(prisonerZn.getPlacenum());
            }
            p.setSrFlag(Constants.Number.NUM_ONE);
        }
        // log.info("预安置人员信息录入【封装总耗时】:{} ms",System.currentTimeMillis() - start);
    }

    /**
     * 5、保存预安置人员(入库方法)
     * @param prisonerMain 主表
     * @param prisonerFx 服刑表
     * @param uploadAppendixFiles 文件上传附件表
     * @param prisonerSrs 社会关系表
     * @param prisonerZns 未成年子女表
     * @param p 标示表
     * @param priNum 罪犯编号（安置生成的）
     * @param account 账号
     * @param level 账号级别
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result saveT(PrisonerMain prisonerMain,PrisonerFx prisonerFx,List<UploadAppendixFiles> uploadAppendixFiles,List<PrisonerSr> prisonerSrs,List<PrisonerZn> prisonerZns,PrisaveTemp p,String priNum,String account,String level) {
        // 1、定义入库开始时间
        long start = System.currentTimeMillis();
        try {
            // 2、为主表、多媒体表、服刑表、社会关系表、子女表、状态表 设置犯罪编号
            prisonerMain.setPriNum(priNum);
            for(UploadAppendixFiles uploadAppendixFile : uploadAppendixFiles) {
                uploadAppendixFile.setPriNum(priNum);
            }
            prisonerFx.setPriNum(priNum);
            for(PrisonerSr prisonerSr : prisonerSrs) {
                prisonerSr.setPriNum(priNum);
            }
            for(PrisonerZn prisonerZn : prisonerZns) {
                prisonerZn.setPriNum(priNum);
            }
            p.setPriNum(priNum);
            // 3、入库主表
            if(null != p.getFxFlag() && null != p.getMainFlag()) {
                if(Constants.Number.NUM_TWO == p.getFxFlag() + p.getMainFlag()) {
                    prisonerMain.setState(Constants.NumberStr.NUM_STR_ONE);
                }
            }
            if(!prisonerMainBatchService.save(prisonerMain)) {
                log.error("主表信息保存失败！");
                throw new RuntimeException("主表信息保存失败");
            }
            List<UploadAppendixFiles> uploadAppendixFiles1 = new ArrayList<>(16);
            String uploadFilePath = FileUtil.getUploadFilePath();
            for(UploadAppendixFiles uploadAppendixFile : uploadAppendixFiles) {
                long next = IdGen.get().next();
                String localCode = CodeUrlUtils.getLocalCode();
                // 广东监狱个性化多媒体的头像和指纹是从别的ftp中读取过来的
                if(Constants.XzqhCode.GUANGDONG.equals(localCode) && Constants.NumberStr.NUM_STR_ZERO_ONE.equals(level)) {
                    String imgId = uploadAppendixFile.getImgId();
                    //1. 判断此人员是否有照片
                    if(Constants.NumberStr.NUM_STR_TWO.equals(imgId)) {
                        //1.ftp获取文件内容以及详细信息(对方的ftp)
                        FTPClient gdFtp = gdFtpUtil.getFTPClientGd();
                        log.info("{}---上传头像信息开始---",prisonerMain.getPName());
                        //ftp:主目录+头像目录+罪犯编号
                        String gdFilePath = gdFtpUtil.getFtpImgPath(uploadAppendixFile.getPriNumGd());
                        //转移到FTP服务器目录
                        try {
                            gdFtp.changeWorkingDirectory(gdFilePath);
                            FTPFile[] fs = gdFtp.listFiles();
                            for(FTPFile ff : fs) {
                                String name = ff.getName();
                                //获取文件类型
                                String type = name.substring(name.lastIndexOf("."));
                                //重新创建上传文件属性
                                String filename = next + type;
                                //本地文件上传的位置
                                String fileAbstractPath = uploadFilePath + uploadAppendixFile.getAccount() + File.separator + filename;
                                File localFile = new File(fileAbstractPath);
                                if(localFile.exists()) {
                                    log.info("{}--本地指纹信息已经存在",prisonerMain.getPName());
                                    continue;
                                } else {
                                    UploadAppendixFiles uploadAppendixFilesTemp = new UploadAppendixFiles();
                                    BeanUtils.copyProperties(uploadAppendixFile,uploadAppendixFilesTemp);
                                    uploadAppendixFilesTemp.setTaskId(Constants.NumberStr.NUM_STR_TWO);
                                    uploadAppendixFilesTemp.setFileName(name);
                                    uploadAppendixFilesTemp.setFileUrl(uploadAppendixFile.getAccount() + File.separator + filename);
                                    OutputStream out = new FileOutputStream(localFile);
                                    // 4.1、将文件上传到本地服务器
                                    boolean b = gdFtp.retrieveFile(name,out);
                                    if(b) {
                                        log.info("{}---本地指纹上传文件成功----",prisonerMain.getPName());
                                        if(localFile.exists()) {
                                            uploadAppendixFiles1.add(uploadAppendixFilesTemp);
                                            // 4.2、将文件上传到ftp服务器
                                            isSaveAppendixFile(fileAbstractPath,uploadAppendixFilesTemp.getAccount());
                                        }
                                    } else {
                                        log.info("{}---本地指纹上传文件失败----",prisonerMain.getPName());
                                    }
                                    out.flush();
                                    out.close();
                                }
                            }
                        } catch(IOException e) {
                            log.info("{}---上传指纹信息出现异常---",prisonerMain.getPName());
                            log.error("发生异常:",e);
                        } finally {
                            log.info("{}---上传头像信息结束---",prisonerMain.getPName());
                            FtpUtil.closeFtpClient(gdFtp);
                        }
                    }
                    //2. 判断此人员是否有指纹
                    String zwStrId = uploadAppendixFile.getZwId();
                    if(Constants.NumberStr.NUM_STR_TWO.equals(zwStrId)) {
                        //1.ftp获取文件内容以及详细信息(对方的ftp)
                        FTPClient gdFtp = gdFtpUtil.getFTPClientGd();
                        log.info("{}---上传指纹信息开始---",prisonerMain.getPName());
                        //ftp:主目录+指纹目录+罪犯编号
                        String gdFilePath = gdFtpUtil.getFtpZwPath(uploadAppendixFile.getPriNumGd());
                        //转移到FTP服务器目录
                        try {
                            gdFtp.changeWorkingDirectory(gdFilePath);
                            FTPFile[] fs = gdFtp.listFiles();
                            for(FTPFile ff : fs) {
                                //文件名字需要做一下
                                String name = ff.getName();
                                //获取文件类型
                                String type = name.substring(name.lastIndexOf("."));
                                //重新创建上传文件属性
                                String filename = next + type;
                                String fileAbstractPath = uploadFilePath + uploadAppendixFile.getAccount() + File.separator + filename;
                                File localFile = new File(fileAbstractPath);
                                if(localFile.exists()) {
                                    log.info("{}--本地头像信息已经存在",prisonerMain.getPName());
                                    continue;
                                } else {
                                    UploadAppendixFiles uploadAppendixFilesTemp = new UploadAppendixFiles();
                                    BeanUtils.copyProperties(uploadAppendixFile,uploadAppendixFilesTemp);
                                    uploadAppendixFilesTemp.setTaskId(Constants.NumberStr.NUM_STR_THREE);
                                    uploadAppendixFilesTemp.setFileName(name);
                                    uploadAppendixFilesTemp.setFileUrl(uploadAppendixFile.getAccount() + File.separator + filename);
                                    OutputStream out = new FileOutputStream(localFile);
                                    // 4.1、将文件上传到本地服务器
                                    boolean b = gdFtp.retrieveFile(name,out);
                                    if(b) {
                                        log.info("{}---本地头像上传文件成功----",prisonerMain.getPName());
                                        if(localFile.exists()) {
                                            uploadAppendixFiles1.add(uploadAppendixFilesTemp);
                                            // 4.2、将文件上传到ftp服务器
                                            isSaveAppendixFile(fileAbstractPath,uploadAppendixFilesTemp.getAccount());
                                        }
                                    } else {
                                        log.info("{}---本地指纹上传文件失败----",prisonerMain.getPName());
                                    }
                                    out.flush();
                                    out.close();
                                }
                            }
                        } catch(IOException e) {
                            log.info("{}---上传头像信息出现异常---",prisonerMain.getPName());
                            log.error("发生异常:",e);
                        } finally {
                            log.info("{}---上传指纹信息结束---",prisonerMain.getPName());
                            FtpUtil.closeFtpClient(gdFtp);
                        }
                    }
                    //3. 如果没有,文件上传表不添加
                    if(!(Constants.NumberStr.NUM_STR_TWO.equals(zwStrId) || Constants.NumberStr.NUM_STR_TWO.equals(imgId))) {
                        log.info("{}--没有头像信息，也没有指纹信息--",prisonerMain.getPName());
                    }
                } else {
                    uploadAppendixFile.setFileName(next + uploadAppendixFile.getFiletype());
                    uploadAppendixFile.setFileUrl(uploadAppendixFile.getAccount() + File.separator + uploadAppendixFile.getFileName());
                    String filename = next + uploadAppendixFile.getFiletype();
                    String tempFileName = uploadAppendixFile.getAccount() + File.separator + next + filename.substring(filename.lastIndexOf('.'));
                    String path = uploadFilePath + uploadAppendixFile.getAccount();
                    String filePath = uploadFilePath + tempFileName;
                    if(null != uploadAppendixFile.getImgstr() && !"".equals(uploadAppendixFile.getImgstr())) {
                        uploadAppendixFiles1.add(uploadAppendixFile);
                        // 4.1、将base64编码转换位图片，存储到服务器本地
                        Base64Util.convertBase64ToFile(uploadAppendixFile.getImgstr(),path,next + uploadAppendixFile.getFiletype());
                        // 4.2、将文件上传到ftp服务器
                        isSaveAppendixFile(filePath,uploadAppendixFile.getAccount());
                    }
                }
            }
            // 5、入库多媒体信息表
            if(!uploadAppendixFileBatchService.saveBatch(uploadAppendixFiles1)) {
                log.error("多媒体信息保存失败！");
                throw new RuntimeException("多媒体信息保存失败");
            }
            // 6、入库服刑表
            if(!prisonerFxBatchService.save(prisonerFx)) {
                log.error("服刑信息保存失败！");
                throw new RuntimeException("服刑信息保存失败");
            }
            // 7、入库社会关系表
            if(!prisonerSrBatchService.saveBatch(prisonerSrs)) {
                log.error("社会关系信息保存失败！");
                throw new RuntimeException("社会关系信息保存失败");
            }
            // 8、入库子女表
            if(!prisonerZnBatchService.saveBatch(prisonerZns)) {
                log.error("子女信息保存失败！");
                throw new RuntimeException("子女信息保存失败");
            }
            // 9、入库状态表
            if(!p.insert()) {
                log.error("状态表保存失败！");
                throw new RuntimeException("状态表保存失败");
            }
        } catch(RuntimeException e) {
            log.error("发生异常：",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failure(ReturnCode.FAILURE);
        }
        // log.info("预安置人员信息录入【入库耗时】:{} ms",System.currentTimeMillis() - start);
        return Result.success(priNum);
    }

    /**
     * 6、上传文件到ftp
     * @param filePath filePath 文件的绝对路径
     * @param account account
     */
    private void isSaveAppendixFile(String filePath,String account) {
        // 异步上传文件到ftp
        asyncUploadFileToFtp.uploadFileToFtp(datapath + account,filePath);
    }

    /**
     * 更新6张表
     * @param data data
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updatePreArrangedPersonnel(String data) {
        // log.info("对外接口入参:{}",data);
        // 定义接口返回message信息
        StringBuilder stringBuilder = new StringBuilder(16);
        // 定义5张表数据对象，用于接收客户端传递的参数
        PrisonerMain prisonerMain = new PrisonerMain();
        List<UploadAppendixFiles> uploadAppendixFiles = new ArrayList<>(16);
        PrisonerFx prisonerFx = null;
        List<PrisonerSr> prisonerSrs;
        List<PrisonerZn> prisonerZns;
        UserInterFaceEntity user = new UserInterFaceEntity();
        Date date1 = new Date();
        prisonerMain.setUpdateUser(user.getAccount());
        prisonerMain.setUpdateTime(date1);
        // 定义PrisaveTemp对象，当另外5张表都保存成功，则添加该表
        //PrisaveTemp p = new PrisaveTemp();
        try {
            // 1、鉴权
            int jq = authentication(data);
            if(Constants.Number.NUM_ONE == jq) {
                stringBuilder.append("鉴权失败-超时");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),null);
            }
            if(Constants.Number.NUM_TWO == jq) {
                stringBuilder.append("鉴权失败-密钥错误");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),null);
            }
            if(Constants.Number.NUM_FU_ONE == jq) {
                stringBuilder.append("请传递时间戳！");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),null);
            }
            if(Constants.Number.NUM_FU_TWO == jq) {
                stringBuilder.append("请传递接口密钥！");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),null);
            }
            if(Constants.Number.NUM_FU_THREE == jq) {
                stringBuilder.append("请传递接口用户！");
                return Result.failure(Constants.Number.NUM_FU_ONE,stringBuilder.toString(),null);
            }
            // 2、check
            Map<String,Object> check = check(data);
            boolean err = (Boolean)check.get("err");
            if(err) {
                List<String> errCodes = (List)check.get("result");
                return Result.failure(Constants.Number.NUM_FU_ONE,"参数校验不通过！",errCodes);
            } else {
                prisonerMain = (PrisonerMain)check.get("PrisonerMain");
                user = (UserInterFaceEntity)check.get("user");
                if(!ObjectUtils.isEmpty(check.get("PrisonerFx"))) {
                    prisonerFx = (PrisonerFx)check.get("PrisonerFx");
                }
                prisonerSrs = (List<PrisonerSr>)check.get("PrisonerSr");
                prisonerZns = (List<PrisonerZn>)check.get("PrisonerZn");
            }
            // 3、更新
            PrisonerMain prisonerMain1 = prisonerMainMapper.selectPrisonerMain(prisonerMain.getPriNum());
            //已经是核查中之后的流程，则不能更新
            if((!Constants.NumberStr.NUM_STR_ZERO.equals(prisonerMain1.getState()) && !Constants.NumberStr.NUM_STR_ONE.equals(prisonerMain1.getState()))) {
                return Result.failure(-50009,"流程中不能修改信息",null);
            }
            boolean mainFlag = false;
            boolean fxFlag = false;
            PrisaveTemp p = new PrisaveTemp();
            p.setUpdateUser(user.getAccount());
            p.setUpdateTime(date1);
            p.setId(IdGen.strid());
            p.setPriNum(prisonerMain1.getPriNum());
            PrisaveTemp pt = p.selectOne(new QueryWrapper<PrisaveTemp>().eq(Constants.StrFinalValue.PRINUM,prisonerMain.getPriNum()));
            if(null != pt) {
                p = pt;
            }
            if(StringUtils.isNotEmpty(prisonerMain.getPName()) && StringUtils.isNotEmpty(prisonerMain.getSex()) && StringUtils.isNotEmpty(prisonerMain.getNationality()) && StringUtils.isNotEmpty(prisonerMain.getIdType()) && null != prisonerMain.getAddtime() && StringUtils.isNotEmpty(prisonerMain.getEducation()) && StringUtils.isNotEmpty(prisonerMain.getPriAddr())) {
                //如果户籍为完整并且农村和城镇
                boolean flag = (Constants.NumberStr.NUM_STR_ZERO_ONE.equals(prisonerMain.getPriAddr()) || Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getPriAddr())) && Constants.NumberStr.NUM_STR_ZERO_ONE.equals(prisonerMain.getHjType());
                if(flag) {
                    if(StringUtils.isNotEmpty(prisonerMain.getNativepro()) && StringUtils.isNotEmpty(prisonerMain.getNativecity()) && StringUtils.isNotEmpty(prisonerMain.getNativecou()) && StringUtils.isNotEmpty(prisonerMain.getNativenum())) {
                        p.setMainFlag(Constants.Number.NUM_ONE);
                        mainFlag = true;
                    }
                } else if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getHjType())) {
                    //如果户籍为查不清人员
                    if(StringUtils.isNotEmpty(prisonerMain.getInvestigatePro()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateCity()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateCou()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateVill()) && StringUtils.isNotEmpty(prisonerMain.getInvestigateNum())) {
                        p.setMainFlag(Constants.Number.NUM_ONE);
                        mainFlag = true;
                    }
                } else {
                    //如果户籍为完整并且非大陆
                    if(StringUtils.isNotEmpty(prisonerMain.getArrestpro()) && StringUtils.isNotEmpty(prisonerMain.getArrestcity()) && StringUtils.isNotEmpty(prisonerMain.getArrestcou()) && StringUtils.isNotEmpty(prisonerMain.getArrestvill()) && StringUtils.isNotEmpty(prisonerMain.getArrestnum())) {
                        p.setMainFlag(Constants.Number.NUM_ONE);
                        mainFlag = true;
                    }
                }
            }
            if(StringUtils.isNotEmpty(prisonerFx.getCritype()) && StringUtils.isNotEmpty(prisonerFx.getPritime()) && StringUtils.isNotEmpty(prisonerFx.getArrJg()) && StringUtils.isNotEmpty(prisonerFx.getPrecri()) && StringUtils.isNotEmpty(prisonerFx.getCanji()) && null != prisonerFx.getPriBegin() && null != prisonerFx.getPriStop() && StringUtils.isNotEmpty(prisonerFx.getAddpenalty()) && StringUtils.isNotEmpty(prisonerFx.getAftype()) && StringUtils.isNotEmpty(prisonerFx.getBqzy())) {
                p.setFxFlag(Constants.Number.NUM_ONE);
                fxFlag = true;
            }
            if(mainFlag && fxFlag) {
                p.setSrFlag(Constants.Number.NUM_ONE);
                p.setZzFlag(Constants.Number.NUM_ONE);
            }
            if(mainFlag && fxFlag) {
                p.setSrFlag(Constants.Number.NUM_ONE);
                p.setZzFlag(Constants.Number.NUM_ONE);
                prisonerMain.setState(Constants.NumberStr.NUM_STR_ONE);
            }
            p.insertOrUpdate();
            prisonerMainMapper.update(prisonerMain,new QueryWrapper<PrisonerMain>().eq("pri_num",prisonerMain.getPriNum()));
            prisonerFx.setUpdateUser(user.getAccount());
            prisonerFx.setUpdateTime(date1);
            prisonerFxMapper.update(prisonerFx,new QueryWrapper<PrisonerFx>().eq("pri_num",prisonerMain.getPriNum()));
            //先删除该犯罪编号全部社会关系(除了监狱添加的社会关系)，然后再遍历新增
            prisonerSrMapper.delete(new QueryWrapper<PrisonerSr>().eq("pri_num",prisonerMain.getPriNum())
                                                                  .le("adduserid",9999));
            for(PrisonerSr prisonerSr : prisonerSrs) {
                prisonerSr.setId(IdGen.strid());
                prisonerSr.setPriNum(prisonerMain.getPriNum());
                prisonerSr.setCreateUser(user.getAccount());
                prisonerSr.setCreateTime(date1);
                prisonerSr.setUpdateUser(user.getAccount());
                prisonerSr.setUpdateTime(date1);
                if(!StringUtils.isEmpty(prisonerSr.getAddrpro())) {
                    String addrproname = (String)stringRedisTemplate.opsForHash()
                                                                    .get("areaCode",prisonerSr.getAddrpro());
                    addrproname = StringUtils.isEmpty(addrproname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrpro()) : addrproname;
                    prisonerSr.setAddrproname(addrproname);
                } else {
                    prisonerSr.setAddrproname("");
                }
                if(!StringUtils.isEmpty(prisonerSr.getAddrcity())) {
                    String addrcityname = (String)stringRedisTemplate.opsForHash()
                                                                     .get("areaCode",prisonerSr.getAddrcity());
                    addrcityname = StringUtils.isEmpty(addrcityname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrcity()) : addrcityname;
                    prisonerSr.setAddrcityname(addrcityname);
                } else {
                    prisonerSr.setAddrcityname("");
                }
                if(!StringUtils.isEmpty(prisonerSr.getAddrcou())) {
                    String addrcouname = (String)stringRedisTemplate.opsForHash()
                                                                    .get("areaCode",prisonerSr.getAddrcou());
                    addrcouname = StringUtils.isEmpty(addrcouname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrcou()) : addrcouname;
                    prisonerSr.setAddrcouname(addrcouname);
                } else {
                    prisonerSr.setAddrcouname("");
                }
                if(!StringUtils.isEmpty(prisonerSr.getAddrvil())) {
                    String addrvilname = (String)stringRedisTemplate.opsForHash()
                                                                    .get("areaCode",prisonerSr.getAddrvil());
                    addrvilname = StringUtils.isEmpty(addrvilname) ? systemCodeMapper.getNameByCode(prisonerSr.getAddrvil()) : addrvilname;
                    prisonerSr.setAddrvilname(addrvilname);
                } else {
                    prisonerSr.setAddrvilname("");
                }
                String addr = new StringBuilder(16).append(prisonerSr.getAddrproname())
                                                   .append(prisonerSr.getAddrcityname())
                                                   .append(prisonerSr.getAddrcouname())
                                                   .append(prisonerSr.getAddrvilname())
                                                   .append(prisonerSr.getAddrdetail()).toString();
                prisonerSr.setAddr(addr);
                prisonerSr.insert();
            }
            //先删除该犯罪编号全部子女信息(除了监狱添加的子女信息)，然后再遍历新增
            prisonerZnMapper.delete(new QueryWrapper<PrisonerZn>().eq("pri_num",prisonerMain.getPriNum())
                                                                  .le("adduserid",9999));
            for(PrisonerZn prisonerZn : prisonerZns) {
                prisonerZn.setId(IdGen.strid());
                prisonerZn.setPriNum(prisonerMain.getPriNum());
                //                prisonerZn.setAdduserid(user.getDepartid());
                prisonerZn.setCreateUser(user.getAccount());
                prisonerZn.setCreateTime(date1);
                prisonerZn.setUpdateUser(user.getAccount());
                prisonerZn.setUpdateTime(date1);
                if(!StringUtils.isEmpty(prisonerZn.getNativepro())) {
                    String nativeproName = (String)stringRedisTemplate.opsForHash()
                                                                      .get("areaCode",prisonerZn.getNativepro());
                    nativeproName = StringUtils.isEmpty(nativeproName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativepro()) : nativeproName;
                    prisonerZn.setNativeproName(nativeproName);
                } else {
                    prisonerZn.setNativeproName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getNativecity())) {
                    String nativecityName = (String)stringRedisTemplate.opsForHash()
                                                                       .get("areaCode",prisonerZn.getNativecity());
                    nativecityName = StringUtils.isEmpty(nativecityName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativecity()) : nativecityName;
                    prisonerZn.setNativecityName(nativecityName);
                } else {
                    prisonerZn.setNativecityName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getNativecou())) {
                    String nativecouName = (String)stringRedisTemplate.opsForHash()
                                                                      .get("areaCode",prisonerZn.getNativecou());
                    nativecouName = StringUtils.isEmpty(nativecouName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativecou()) : nativecouName;
                    prisonerZn.setNativecouName(nativecouName);
                } else {
                    prisonerZn.setNativecouName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getNativevill())) {
                    String nativevillName = (String)stringRedisTemplate.opsForHash()
                                                                       .get("areaCode",prisonerZn.getNativevill());
                    nativevillName = StringUtils.isEmpty(nativevillName) ? systemCodeMapper.getNameByCode(prisonerZn.getNativevill()) : nativevillName;
                    prisonerZn.setNativevillName(nativevillName);
                } else {
                    prisonerZn.setNativevillName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getPlacepro())) {
                    String placeproName = (String)stringRedisTemplate.opsForHash()
                                                                     .get("areaCode",prisonerZn.getPlacepro());
                    placeproName = StringUtils.isEmpty(placeproName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacepro()) : placeproName;
                    prisonerZn.setPlaceproName(placeproName);
                } else {
                    prisonerZn.setPlaceproName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getPlacecity())) {
                    String placecityName = (String)stringRedisTemplate.opsForHash()
                                                                      .get("areaCode",prisonerZn.getPlacecity());
                    placecityName = StringUtils.isEmpty(placecityName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacecity()) : placecityName;
                    prisonerZn.setPlacecityName(placecityName);
                } else {
                    prisonerZn.setPlacecityName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getPlacecou())) {
                    String placecouName = (String)stringRedisTemplate.opsForHash()
                                                                     .get("areaCode",prisonerZn.getPlacecou());
                    placecouName = StringUtils.isEmpty(placecouName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacecou()) : placecouName;
                    prisonerZn.setPlacecouName(placecouName);
                } else {
                    prisonerZn.setPlacecouName("");
                }
                if(!StringUtils.isEmpty(prisonerZn.getPlacevill())) {
                    String placevillName = (String)stringRedisTemplate.opsForHash()
                                                                      .get("areaCode",prisonerZn.getPlacevill());
                    placevillName = StringUtils.isEmpty(placevillName) ? systemCodeMapper.getNameByCode(prisonerZn.getPlacevill()) : placevillName;
                    prisonerZn.setPlacevillName(placevillName);
                } else {
                    prisonerZn.setPlacevillName("");
                }
                String hujidi = new StringBuilder(16).append(prisonerZn.getNativeproName())
                                                     .append(prisonerZn.getNativecityName())
                                                     .append(prisonerZn.getNativecouName())
                                                     .append(prisonerZn.getNativevillName())
                                                     .append(prisonerZn.getNativenum()).toString();
                prisonerZn.setHujidi(hujidi);
                String juzhudi = new StringBuilder(16).append(prisonerZn.getPlaceproName())
                                                      .append(prisonerZn.getPlacecityName())
                                                      .append(prisonerZn.getPlacecouName())
                                                      .append(prisonerZn.getPlacevillName())
                                                      .append(prisonerZn.getPlacenum()).toString();
                prisonerZn.setJuzhudi(juzhudi);
                prisonerZn.insert();
            }
        } catch(RuntimeException e) {
            log.error("发生异常:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failure(ReturnCode.FAILURE);
        }
        return Result.success(prisonerMain.getPriNum());
    }

    /**
     * 根据行政区划全名查询各级编码及名称 todo:这个后续改成mybatis方式查询
     * @param fullAreaName fullAreaName
     * @return Map
     */
    @Override
    public Map<String,Object> getAllArea(String fullAreaName) {
        String areaSql = "select * from area_code_full where full_name = \'" + fullAreaName + "\' limit 1";
        Map<String,Object> stringObjectMap;
        try {
            stringObjectMap = jdbcTemplate.queryForMap(areaSql);
        } catch(EmptyResultDataAccessException emptyResultDataAccessException) {
            stringObjectMap = new HashMap<>(16);
        }
        return stringObjectMap;
    }

    /**
     * 模糊查询 - 根据行政区划全名查询各级编码及名称
     * @param fullAreaName fullAreaName
     * @return Map
     */
    @Override
    public Map<String,Object> getVagueAllArea(String fullAreaName) {
        String areaSql = "select * from area_code_full where full_name like \'" + fullAreaName + "%\' limit 1";
        Map<String,Object> stringObjectMap;
        try {
            stringObjectMap = jdbcTemplate.queryForMap(areaSql);
        } catch(EmptyResultDataAccessException emptyResultDataAccessException) {
            stringObjectMap = new HashMap<>(16);
        }
        return stringObjectMap;
    }

    /**
     * 3.参数校验入口
     * @param data data
     * @return Map<String,Object>
     */
    private Map<String,Object> checkCjpg(String data) {
        // 用于保存返回的错误code集合
        List<String> errCodes = new ArrayList<>(16);
        long start = System.currentTimeMillis();
        Map<String,Object> result = new HashMap<>(16);
        Map<String,Object> maps = JsonUtil.toMap(data);
        UserInterFaceEntity userDTO = JsonUtil.toBean(maps.get("user").toString(),UserInterFaceEntity.class);
        // 取出各表不需要校验的字段
        String unCheckField = userDTO.getUnCheckField();
        String[] strs = unCheckField.split("\\|");
        List<String> cjpg = Arrays.asList(strs[5].split(","));
        // 4 check 出监评估
        {
            Map<String,Object> cjpgMap = JsonUtil.toMap(maps.get("cjpg").toString());
            if(null == cjpgMap) {
                cjpgMap = new HashMap<>(16);
            }
            for(Map.Entry<String,Object> next : cjpgMap.entrySet()) {
                Object obj = next.getValue();
                if(obj instanceof String) {
                    next.setValue(((String)obj).trim());
                }
            }
            // 取出prisonerMainMap并校验
            String amnesty = (String)cjpgMap.get("amnesty");
            String zfz = (String)cjpgMap.get("zfz");
            String death = (String)cjpgMap.get("death");
            String zrsqjz = (String)cjpgMap.get("zrsqjz");
            String wushe = (String)cjpgMap.get("wushe");
            String sishi = (String)cjpgMap.get("sishi");
            String gaizao = (String)cjpgMap.get("gaizao");
            String renzui = (String)cjpgMap.get("renzui");
            String xinli = (String)cjpgMap.get("xinli");
            String lianxi = (String)cjpgMap.get("lianxi");
            String baowaijiuyi = (String)cjpgMap.get("baowaijiuyi");
            String sanwu = (String)cjpgMap.get("sanwu");
            String sanjia = (String)cjpgMap.get("sanjia");
            String weifa = (String)cjpgMap.get("weifa");
            String aftype = (String)cjpgMap.get("Aftype");
            String canji = (String)cjpgMap.get("canji");
            String gdzs = (String)cjpgMap.get("gdzs");
            String shjw = (String)cjpgMap.get("shjw");
            String jtbh = (String)cjpgMap.get("jtbh");
            String xshkn = (String)cjpgMap.get("xshkn");
            String jiuzhujianyi = (String)cjpgMap.get("jiuzhujianyi");
            if(!cjpg.contains("amnesty") && StringUtils.isEmpty(amnesty)) {
                errCodes.add("700001");
            }
            if(!cjpg.contains("zfz") && StringUtils.isEmpty(zfz)) {
                errCodes.add("700002");
            }
            if(!cjpg.contains("death") && StringUtils.isEmpty(death)) {
                errCodes.add("700003");
            }
            if(!cjpg.contains("zrsqjz") && StringUtils.isEmpty(zrsqjz)) {
                errCodes.add("700004");
            }
            if(!cjpg.contains("wushe") && StringUtils.isEmpty(wushe)) {
                errCodes.add("700005");
            }
            if(!cjpg.contains("sishi") && StringUtils.isEmpty(sishi)) {
                errCodes.add("700006");
            }
            if(!cjpg.contains("gaizao") && StringUtils.isEmpty(gaizao)) {
                errCodes.add("700007");
            }
            if(!cjpg.contains("renzui") && StringUtils.isEmpty(renzui)) {
                errCodes.add("700008");
            }
            if(!cjpg.contains("xinli") && StringUtils.isEmpty(xinli)) {
                errCodes.add("700009");
            }
            if(!cjpg.contains("lianxi") && StringUtils.isEmpty(lianxi)) {
                errCodes.add("700010");
            }
            if(!cjpg.contains("baowaijiuyi") && StringUtils.isEmpty(baowaijiuyi)) {
                errCodes.add("700011");
            }
            if(!cjpg.contains("sanwu") && StringUtils.isEmpty(sanwu)) {
                errCodes.add("700012");
            }
            if(!cjpg.contains("sanjia") && StringUtils.isEmpty(sanjia)) {
                errCodes.add("700013");
            }
            if(!cjpg.contains("weifa") && StringUtils.isEmpty(weifa)) {
                errCodes.add("700014");
            }
            if(!cjpg.contains("Aftype") && StringUtils.isEmpty(aftype)) {
                errCodes.add("700015");
            }
            if(!cjpg.contains("canji") && StringUtils.isEmpty(canji)) {
                errCodes.add("700016");
            }
            if(!cjpg.contains("gdzs") && StringUtils.isEmpty(gdzs)) {
                errCodes.add("700017");
            }
            if(!cjpg.contains("shjw") && StringUtils.isEmpty(shjw)) {
                errCodes.add("700018");
            }
            if(!cjpg.contains("jtbh") && StringUtils.isEmpty(jtbh)) {
                errCodes.add("700019");
            }
            if(!cjpg.contains("xshkn") && StringUtils.isEmpty(xshkn)) {
                errCodes.add("700020");
            }
            if(!cjpg.contains("jiuzhujianyi") && StringUtils.isEmpty(jiuzhujianyi)) {
                errCodes.add("700021");
            }
        }
        // 7、封装返回结果
        if(!errCodes.isEmpty()) {
            result.put("err",true);
            result.put("result",errCodes);
        } else {
            result.put("err",false);
            result.put("cjpg",cjpg);
        }
        log.info("预安置人员信息录入【出监评估校验耗时】:{} ms",System.currentTimeMillis() - start);
        return result;
    }

    boolean check() {
        return false;
    }

    /**
     * todo 针对于重庆市直辖区县行政编码错误情况做的应急处理，后续要删除
     * @param cityCode 传过来的重庆市行政区划 - 500200
     * @return 返回的系统内的重庆市行政区划 - 500100
     */
    private String cityCheck(String cityCode) {
        return "500200".equals(cityCode) ? "500100" : cityCode;
    }
}